var foo = document.getElementsByClassName("foo");
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:
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!
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
[...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>