Hommer Smith
Hommer Smith

Reputation: 27852

Targeting second span in li element

I have the following markup:

<li>
<span>Hi</span>
<a href="#">Link</a>
<span>Bye</span>
</li>

How can I target the second span? I don't want to access the third child of li, but the second span in li.

Upvotes: 4

Views: 8356

Answers (4)

user240141
user240141

Reputation:

Give it a shot : Add jquery reference and use this script

<script>
    $("li span:nth-child(2)").append("<span> - 2nd!</span>");
</script>

Upvotes: 0

Sean Keating
Sean Keating

Reputation: 1728

Use a jquery selector with CSS nth-child.

$('li span:nth-child(2)')

Upvotes: 2

Nope
Nope

Reputation: 22329

You can use jQuery's eq() selector to get the second span in the li element.

$("li span").eq(1)

eq() will return a jQuery object with a reference to the second span. So you can continue calling jQuery methods on it.

If you rather get the HTML element of the second span you could use this instead:

$("li span")[1];

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could try the following selector:

$('li').children('span').eq(1);

Upvotes: 0

Related Questions