user31782 user31782 - 6 months ago 10
HTML Question

How to select last element with jquery?

I want to select the last

audio
element on my webpage http://sycoscientistrecords.github.io/ I tried:

$(" audio:last-of-type");


The problem is that it returns all the
audio
elements:

Object { length: 12, prevObject: Object, context: HTMLDocument → index.html, selector: " audio:last-of-type", 12 more… }


There are 12 audio elements on the page and the jquery selector returns all of them.

So, How do I select last element with jquery?

Answer

Use last(). You could use the :last selector too, but then it can't be passed directly to the browser's selector engine.

$("audio").last()

Why doesn't last-of-type work?

The jQuery docs for the selector says:

Selects all elements that are the last among siblings of the same element name.

So in your case it would be matching all the last audio elements that were inside of other elements.

Comments