Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the last element of an anonymous HTMLCollection

My vanilla Javascript code contains many constructs like this:

var foo = document.getElementsByClassName("foo")[0];

This works well whenever I want the first instance of foo (or when there is only one instance of foo). But, what if I want the last instance of foo?

I can of course do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var fooCollection = document.getElementsByClassName("foo");
var foo = foo[fooCollection.length - 1];

Call me petty, but I dislike the fact that this requires two lines and an intermediate named variable, not to mention some potential for a silly off-by-one error due to zero indexing. Is there a way to get the last instance of foo as simply as I can get the first instance?

"No, there’s no reasonable way to do that and you’re being silly" is a perfectly acceptable answer to this question!

>Solution :

Not as simply since getElementsByClassName returns a live node list and not an array.

You could convert it into an array though. Then, in supporting browsers, you can use the at method.

[...document.getElementsByClassName('foo')].at(-1).style.background = "red";
<div class="foo">X</div>
<div class="foo">X</div>
<div class="foo">X</div>
<div class="foo">X</div>
<div class="foo">X</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading