I’ve been getting a bit frustrated with jQuery on a demo I’m slapping together and was wondering if the following is just a limitation of jQuery’s selector and search methods, or I’m just using it wrong.
Here’s an example HTML block:
<div class='div_item'>
<td class='list'>
<dl><dt class="access_text">Div1 text1</dt></dl>
<dl><dt class="access_text">Div1 text2</dt></dl>
<dl><dt class="access_text">Div1 text3</dt></dl>
</td>
</div>
<div class='div_item'>
<td class='list'>
<dl><dt class="access_text">Div2 text1</dt></dl>
<dl><dt class="access_text">Div2 text2</dt></dl>
<dl><dt class="access_text">Div2 text3</dt></dl>
</td>
</div>
Here’s the jQuery 1.9.2 script:
$().ready(function(){
$('.div_item'); // this is a 2 jQuery array, with no children
$('.div_item').find('.access_text'); // This is empty, length 0, .div_item's children aren't populated. Like I was using .children()
$('.div_item').find('.access_text').each(function() { // This doesn't work because the .div_item children aren't populated?
alert($(this).innerText);
}):
});
My question is, is there a reason why are the children in the $('.div_item') array objects not populated? If they’re not populated, they can’t be referenced, then can’t be .find()‘ed for properly. This is where I think my usage is the problem.
All the suggestions I’ve seen so far work for a flatter DOM. e.g. <div class='div_item'><dt class="access_text"></dt></div>, but not for something that’s further nested.
Ok!!! If anyone is curious and thought I’ve been crazy all this time, try testing it yourself. The above jQuery + the updated HTML sample WITH wrapping tags!
I was testing the divs within a table and it probably found a gap in the DOM parsing. I know that div’s aren’t supposed to be inserted in between and it’s elements, but I never expected it to surprise me like this!
Here’s the bad html that’s fail the jQuery find: (no child elements)
Here’s how I adjusted it to work with jQuery:
The tr class is now found by the query. In the previous case, the div’s children weren’t populated, but the div’s themselves were returned.
Very tricky…
Note that this was a sample and was adapted from my other work, so I appologize if there were any confusing typos.