jQuery get tag in tag with selectors
I have the following html code:
<div id="test">
<nav>
<ul>
<li>One</li>
<li>Two</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
</ul>
<ul>
<li>One</li>
<li>Two</li>
</ul>
</nav>
<开发者_如何学运维/div>
I want to add an li to the bottom of the first ul.
I'm sure I have seen somewhere something like $("test:nav:ul")
,
but I cant find any help about something similar,
could you guys please help me?
Use this:
$('#test ul:first').append('<li>anything inside li</li>');
or if performance matters, use:
$('#test ul').filter(':first').append('<li>something here</li>');
or you can also use:
$('#test ul').first().append('<li>something here</li');
even you can go backwards:
$('<li>something</li>').appendTo('#test ul:first');
You're looking for the descendant selector: $('#test nav ul:first')
$("#test ul:first").append("<li></li>");
:first
selects the first matched element, in this case the first ul
.
$("#test nav ul:first").append('<li>Three</li>');
If you are using IE <= 8, then use this:
$("#test ul:first").append('<li>Three</li>');
The #
means ID=
. The spaces between the terms mean "descendant". And :first
gets the 1st element from the set (UL
in this case). Since the ULs are a descendant of #test
the selector, nav
isn't really needed.
You could get it with something like this,
$('ul').first()
o just add an id to the ul and get it by id with
$('#id')
精彩评论