I have the following html:
<ul>
<li>
<a href="#">link 1</a>
<ul>
<li><a href="#">link 2</a></li>
<li><a href="#">link 3</a></li>
<li><a href="#">link 4</a></li>
</ul>
</li>
<li>
<a href="#">link 5</a>
<ul>
<li><a href="#">link 6</a></li>
<li><a href="#">link 7</a></li>
<li><a href="#">link 8</a></li>
</ul>
</li>
</ul>
I wish to return link 1 and link 5 in jQuery. I have got as far as:
$('ul li a:first-child').each(function(e){
$(this).css('color','blue');
});
However it returns all nodes, any advice appreciated!
Description. "$("ul li:first")" get only the first <li> element of the <ul>.
The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).
Definition and UsageThe :first-child selector selects all elements that are the first child of their parent. Tip: Use the :last-child selector to select elements that are the last child of their parent.
You can use $('li'). parent(). attr('id') to get the id of the parent element.
It appears that you don't simply want "the first and fifth" link, but instead the first link within immediate list-items of your main UL. Your syntax was nearly correct.
$("ul.myList > li > a:first-child").css("color", "blue");
In this example the > signifies immediacy. When we say > li
, we don't mean just any LI that happens to be in the UL, we mean the immediate li's. The same goes for the links.
Note also that I'm using a classname on my UL to distinguish it from just any UL. If we don't, the inner UL will be included in this selector.
Keeping in mind that jQuery uses a zero-based index (meaning the first element is index 0, the second is index 1, etc), we can use the :eq() selector to get specific indexes. In this case, we want 1 and 5 so we ask for 0 and 4:
$("a:eq(0), a:eq(4)", "ul.myLinks").css("color", "blue");
The second parameter of the selector ul.myLinks
is our context. I'm assuming these links exist within an unordered-list having a classname of "myLinks".
<ul class="myLinks">
<li><a href="#0">I'm Blue!</a></li> <!-- this will be blue -->
<li><a href="#1">Foo</a></li>
<li><a href="#2">Foo</a>
<ul>
<li><a href="#3">Foo</a></li>
<li><a href="#4">I'm Blue!</a></li> <!-- this will be blue -->
</li>
</ul>
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