For now there is no direct native way to get the element inside containers "nested". For now you can have a consumable method:
(I 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 in 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 goes the explanation:
findLastNestedContainer
takes an HTML container and continuously checks the first child element that the current container has, until no more HTML elements appear inside it, finally returns the last verified container.
Example of use:
findLastNestedContainer(elementoHTML)
This function will allow you to directly capture an (first) element within containers nested, not just inside a little elephant.
If you want to take the last element inside (one or several) HTML elements, just modify the condition inside the loop for
in the function block findLastNestedContainer
, to take the last element of the current container’s children 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;
Have you seen my answer below ?
– Klaider
@Someone saw yes, from what I understood, is exactly what I want, but it turned out that I found a less complex way to get the element I need, I used the id of another element and added a keyword, in my case it became simpler and with less code. But that’s what I had been researching and couldn’t find, thank you.
– Bruno
@Bruno, I posted an answer with the solution using jQuery.... I think it’s simpler... unless you don’t want to use jQuery... : D
– Marllon Nasser
@Marllonnasser, I have nothing against jQuery kkkkkkk, I even use it a lot, but in my problem it could not be applied because of the selection of the element, but it is interesting as well. But I was left a question, in your answer you used ". html()" that searches everywhere on the page, could be changed to some specific element?
– Bruno
Why is element selection a problem? Don’t you have a definition of what you’re looking for? It’s not always a
span
within atd
?– Marllon Nasser
@Marllonnasser, wow, sorry, I was still with an idea to use the class in the selection. In this case it’s not a problem, it’s always that.
– Bruno
So... there. in my opinion is a more "clean solution".
– Marllon Nasser