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.
Well you code is not really correct. .find() does not expect a function as parameter but a selector, a jquery object or a DOM element.
Looking at the value of this
within your callback in the find method, it refers to the document, and not you <div>
as you expect.
Here's a correct code:
$(document).ready(function(){
// cannot use .children() because the <dt> are not direct children
$('.div_item').find('.access_text').each(function() {
alert(this.innerText);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With