Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Immediate children

I have a structure like this:

<ul id="mycustomid">
    <li><a>Item A</a>
        <ul class="children">
           <li><a>Child1 of A</a>
               <ul class="children">
                 <li><a>Grandchild of A</a>
                    <ul class="children">
                       <li><a>Grand Grand child of A</a></li>
                    </ul>
                </li>
               </ul>
           </li>
        </ul>
    </li>
    <li><a>Item B</a></li>
    <li><a>Item C</a></li>
</ul>

Now, I am using Jquery to get only the immediate children of the ul#mycustomid. But my code returns me with ALL the li's in my structure. How should I proceed?

Here's my code:

$(document).ready(function() {
 var arri = $("#mycustomid>li").text();
 alert(arri);
});

I have tried .children() too, it gives me almost the same result. This is really getting on my nerves :(

My alert box outputs exactly as shown below (including those white gaps):

Item A 
Child1 of A
Grandchild of A

Grand Grandchild of A


ItemBItemC

Whereas, it should be just (without spaces):

Item A 
Item B
Item C

To understand my problem, you can check out the live version at https://jsfiddle.net/yS6ZJ/

Please point me in the right direction.

like image 649
dsignr Avatar asked Jul 02 '10 13:07

dsignr


2 Answers

I think that your selector is working just fine - it's what you're doing with it that's got a problem.

When you call .text(), you get all the contents of the element. All of it, including the child elements.

Try this:

$('#mycustomid > li').each(function() {
  alert($(this).find('a:eq(0)').text());
});
like image 84
Pointy Avatar answered Oct 05 '22 13:10

Pointy


This will solve your issue:

$(document).ready(function() {
  var arri=$("#mycustomid > li").children('a').append('\n').text();
  alert(arri);
});

The append('\n') is there just to add a line break, so that it looks okay in the alert.

To include all grandchildren, you just remove the immediate reference to LI:

$(document).ready(function() {
  var arri=$("#mycustomid li").children('a').append('\n').text();
  alert(arri);
});

And to just get the grandchildren:

$(document).ready(function() {
  var arri=$("#mycustomid li").not("#mycustomid > li").children('a').append('\n').text();
  alert(arri);
});

And to get each level, you can go for:

$(document).ready(function() {
  var ChildOfA=$("#mycustomid > li > ul > li > a").append('\n').text();
  var GrandchildOfA=$("#mycustomid > li > ul > li > ul > li > a").append('\n').text();
  var GrandGrandChildOfA=$("#mycustomid > li > ul > li > ul > li > ul > li > a").append('\n').text();
  alert('List of Child1 of A children:\n\n'+ChildOfA+'\n\n'+
        'List of Grandchild of A children:\n\n'+GrandchildOfA+'\n\n'+
        'List of Grand Grand child of A children:\n\n'+GrandGrandChildOfA);
});
like image 29
Gert Grenander Avatar answered Oct 05 '22 11:10

Gert Grenander