terrid25
terrid25

Reputation: 1946

jQuery - find last occurrence of a div

I have 2 divs, with the same id, pagination, one is at the top of the page, the other at the bottom.

What I'd like to do, is find the last id, so this would be the <div id="pagination"></div> at the bottom of the page and add some more HTML, so it looks like:

<div id="pagination"></div><hr />

Is this possible in jQuery?

Upvotes: 12

Views: 22920

Answers (7)

Scoobler
Scoobler

Reputation: 9719

If you were being correct, you should never have two ID's the same, so using $('#selector:last') or $('#selector').last() won't work, however you can cheat a little like this:

$("div[id=pagination]:last").......

Here is an example

Upvotes: 6

Deele
Deele

Reputation: 3684

You cant use same ID in one page. The ID is unique identifier, If you need use identifier more than once, use class instead.

Any way, you can use :last selector, like this:

$("div:last")

You could eaven use :last-child, like this:

$('#pagination:last-child')

Upvotes: 25

manji
manji

Reputation: 47978

.last()

$('div#pagination').last()

Upvotes: 3

Sudhir Jonathan
Sudhir Jonathan

Reputation: 17516

I'd suggest adding the pagination class to both the divs (you can't have duplicate IDs) and using $('div.pagination:last') to grab the last one on the page.

Upvotes: 1

Faber
Faber

Reputation: 2194

yes, you can get the array of divs with the same ID

var myDivArray = $('#pagination');

And then you can get the second element

var myDiv = myDivArray[1];

I hope it's helpful

Upvotes: 0

Swaff
Swaff

Reputation: 13621

Having two elements with the same ID is not valid html.

Instead use differnet classes, e.g. pag_top, pag_bottom and select the bottom one using:

$(".pag_bottom")

Upvotes: 0

Headshota
Headshota

Reputation: 21449

you can't have multiple elements with the same ID, id must be unique.

but if you want the last occuranse of the element you can use this

$('selector:last')

Upvotes: 0

Related Questions