JQuery gets first link from li elements
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 want to return link 1 and link 5 in jQuery. I got to:
$('ul li a:first-child').each(function(e){
$(this).css('color','blue');
});
However, it returns all nodes, any advice is appreciated!
+5
2 answers
Get a direct link to all items in an instant list
It sounds like you just don't need the first and fifth link, but instead the first link inside the closest list elements of your main UL. Your syntax was almost correct.
$("ul.myList > li > a:first-child").css("color", "blue");
In this example,> means immediacy. When we say > li, we do not mean only the LI that happens in UL, we mean the immediate li. The same goes for links.
, UL, UL. , UL .
,
, jQuery ( , 0, - 1 ..), : eq() . 1 5, 0 4:
$("a:eq(0), a:eq(4)", "ul.myLinks").css("color", "blue");
ul.myLinks - . , , "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>
+5