Frank
Frank

Reputation: 1864

jQuery :last selector

I am using this jQuery code

$('#share_module:last').css("background-color","red");

but it always does it to the first #share_module

The HTML structure goes some what like this

<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>
<div id = "share_module" class = "id of the share">
//then stuff inside
</div>

But it just gets the first one. Could anybody help?

Upvotes: 2

Views: 282

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

You cannot have multiple DOM elements with the same id. That's just invalid HTML. Start by fixing your markup and remove this id attribute or at least provide an unique id if you ever expect your script to behave as expected. So if you want to use the :last selector you could use a class selector instead of an id selector for example (it doesn't make sense to use the :last selector with an id selector because an id selector returns only a single DOM element => as you can have only one element with this id in your DOM => makes sense):

<div class="share_module" >
    //then stuff inside
</div>
<div class="share_module" >
    //then stuff inside
</div>
<div class="share_module" >
    //then stuff inside
</div>
<div class="share_module" >
    //then stuff inside
</div>
<div class="share_module" >
    //then stuff inside
</div>

and once you have valid markup you can use the :last selector:

$('.share_module:last').css("background-color","red");

and here's a live demo.

Upvotes: 11

Related Questions