How to get last generic child node with jquery?
css, html, jquery
Solution
The easiest way with single statement/selector:
$("#nav").children().each(function(i, item) {
alert($(item).find(':not(:has(*))').text());
});
JSFiddle: http://jsfiddle.net/qUx4A/
A little explanation:
$("#nav").children().each() - do the body for each element in the #nav element (for each li, a, div....
:has(*) - select element, that has any child element
- :not(:has(*)) - negative of 2. (select element that has NOT any child element) - most inner
- .text() - text content of such most inner element
Hope, that's enought, I'm not sure I can explain it more precise. :)
Problem
i have about 4000 websites, all have slightly different navigation html, but the end child node is always a text based node and there is no real uniformity to how the html is laid out. how would i get the last child node for each of the li's or a's or div's in a generic mannor based on the following html examples ``` <!-- want to be able to get each span and its text --> <ul id="nav"> <li><a href="#"><span>Menu Item</span></a></li> <li><a href="#"><span>Menu Item</span></a></li> <li><a href="#"><span>Menu Item</span></a></li> </ul> <!-- want to be able to get each a and its text --> <ul id="nav"> <li><a href="#">Menu Item</a></li> <li><a href="#">Menu Item</a></li> <li><a href="#">Menu Item</a></li> </ul> <!-- want to be able to get each a and its text --> <div id="nav"> <div><a href="#">Menu Item</a></div> <div><a href="#">Menu Item</a></div> <div><a href="#">Menu Item</a></div> </div> <!-- want to be able to get each a and its text --> <div id="nav"> <a href="#">Menu Item</a> <a href="#">Menu Item</a> <a href="#">Menu Item</a> </div> ``` these are just some of the ways that nav's have been implemented in some of the sites, all usually have a root element with the id of nav, followed by a set of children, which can have grandchildren and further. i do not want to have to write a separate selector for each one, so i was trying to find a generic way to do each on the first child within #nav, which would then find the last child of that particular element that contained some text. so far i have only managed to write anything that requires a custom selector for each type of nav, so im afraid i dont have any code to start with to post. does anyone have any idea how they would find these final children with jquery?