0

I have this ul li list:

<ul>
  <li><div>Text</div><a href="#">A</a></li>
  <li><div>Text</div><a href="#">B</a></li>
  <li><div>Text</div><a href="#">C</a></li>
  <li>
    <ul>
      <li><div>Text</div><a href="#">A1</a></li>
      <li><div>Text</div><a href="#">B1</a></li>
      <li><div>Text</div><a href="#">C1</a></li>
      <li><div>Text</div><a href="#">D1</a></li>
    </ul>
  </li>
  <li><div>Text</div><a href="#">E</a></li>
</ul>

I need to choose all "li" element from the first level.

In this example it will be:

  <li><div>Text</div><a href="#">A</a></li>
  <li><div>Text</div><a href="#">B</a></li>
  <li><div>Text</div><a href="#">C</a></li>
  <li><div>Text</div><a href="#">E</a></li>

Trying to use:

  $('ul').children()

I get all "li" elements from the first level and second level.

Thank you very much.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
kevas
  • 551
  • 2
  • 7
  • 22
  • That's because you're matching all the `
      ` elements, at any level. You have to identify the `
        ` element you're interested in (e.g. through `id` or `class`) in order to achieve what you want.
    – Frédéric Hamidi Dec 29 '14 at 10:42
  • possible duplicate of [Selecting only first-level elements in jquery](http://stackoverflow.com/questions/977883/selecting-only-first-level-elements-in-jquery) – Sudharsan S Dec 29 '14 at 10:47
  • _"I need to choose all "li" element from the first level."_ - No, in your example you indicate that you want all first-level li elements that don't contain a ul, as compared to *all* first-level li elements. In any case, is there any reason why you can't give the ul in question an id or class? – nnnnnn Dec 29 '14 at 11:02

6 Answers6

4

Select li of ul:first which doesnot has a ul element as child.

$('ul:first').children('li:not(:has(ul))');

Fiddle

Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
Okky
  • 10,338
  • 15
  • 75
  • 122
  • 3
    Note that this only works for the html snippet shown. If that were part of a larger page with other ul elements above it then obviously [it wouldn't work](http://jsfiddle.net/9mbxcap5/1/). – nnnnnn Dec 29 '14 at 11:03
1

You can use following code which will search for 1st ul and then all li's: $('ul:first>li')

Research
  • 11
  • 4
0

You can add a class to the first ul and then call .children()

0

try

$('ul>li').css(//your doing//);

This will select the direct childs of the all ul tags in your code.

If you want to acess specific ul, try givig it a class or id.

Rahul Munjal
  • 2,551
  • 2
  • 15
  • 35
-1

You could change your selector to

$("'whatever element is above first level ul element' > ul > li")
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
Michael
  • 436
  • 3
  • 15
-1

Give the external ul a class:

<ul class="my_ul">
....
</ul>

and in jquery you an get them like:

  $('.my_ul').children()

EDIT: my first code was getting al children.

Ali insan Soyaslan
  • 836
  • 5
  • 14
  • 33