Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find, each, children and accessing sub-children [closed]

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.

like image 827
dubmojo Avatar asked Dec 03 '11 18:12

dubmojo


1 Answers

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);
    });
});
like image 94
Didier Ghys Avatar answered Sep 19 '22 12:09

Didier Ghys