For now there is no direct native way to get the element inside containers "nested" . For now you can have a consumable method:
(I'll warn you that I will not implement this method within HTMLElement#
for two reasons:
- Not all browsers have this interface
HTMLElement
;
- can be problematic with libraries
)
Example to work across multiple browsers. Note: You may notice that I used #childNodes
instead of #children
, some old browsers do not support #children
.
var castCollection,
findLastNestedContainer;
findLastNestedContainer = function(container) {
var child;
for (; child = castCollection(container.childNodes)[0];)
container = child;
return container;
};
castCollection = function(collection) {
var revised = [];
var i, len, node;
i = 0;
len = collection.length;
for (; i < len; ++i) {
node = collection[i];
if ((typeof node.nodeValue) !== "string")
revised.push(node);
}
return revised;
};
Now finally the explanation goes:
-
findLastNestedContainer
takes an HTML container and continuously checks the first child element that the current container has, until no HTML element appears within it, finally returns the last container checked.
Example usage:
findLastNestedContainer(elementoHTML)
This function will allow you to directly capture a (first) element inside nested containers, not just inside an element.
If you want to get the last element inside (one or more) HTML elements, simply modify the condition inside the for
loop in the findLastNestedContainer
function block, to get the last element of the current container's child collection :
// Eu sei que poderia ter sido usado Array#last,
// mas nem todos navegadores suportam o getter
for (; (child = castCollection(container.childNodes))[child.length - 1];)
container = child;