Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting only first-level elements in jquery

How can I select the link elements of only the parent <ul> from a list like this?

<ul> <li><a href="#">Link</a></li> <li><a href="#">Link</a>   <ul>     <li><a href="#">Link</a></li>     <li><a href="#">Link</a></li>     <li><a href="#">Link</a></li>     <li><a href="#">Link</a></li>     <li><a href="#">Link</a></li>   </ul> </li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> 

So in css ul li a, but not ul li ul li a

Thanks

like image 631
aston Avatar asked Jun 10 '09 20:06

aston


People also ask

Which selector select the first element of the tag in jQuery?

The :first selector selects the first element.

What is the correct way to select all the first level paragraphs of a certain element?

Element Selectors The most basic of the selectors is an element selector. For example, paragraphs in an HTML document are represented by the p element and wrapped in <p></p> tags. To select all paragraphs in a document we would use the following selector. To select all level 1 headings we would use the h1 selector.

How do you select an element by index?

The :eq() selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). This is mostly used together with another selector to select a specifically indexed element in a group (like in the example above).

How do you select elements in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


2 Answers

$("ul > li a") 

But you would need to set a class on the root ul if you specifically want to target the outermost ul:

<ul class="rootlist"> ... 

Then it's:

$("ul.rootlist > li a").... 

Another way of making sure you only have the root li elements:

$("ul > li a").not("ul li ul a") 

It looks kludgy, but it should do the trick

like image 94
Philippe Leybaert Avatar answered Oct 01 '22 04:10

Philippe Leybaert


Once you have the initial ul, you can use the children() method, which will only consider the immediate children of the element. As @activa points out, one way to easily select the root element is to give it a class or an id. The following assumes you have a root ul with id root.

$('ul#root').children('li'); 
like image 38
tvanfosson Avatar answered Oct 01 '22 06:10

tvanfosson