简体   繁体   中英

How to check if an element is the last with this class?

So if I have a list of elements and I want to find out which one of them is the last one with this class. How can I do it without JQuery? Maybe I can get its index somehow?

in JQuery it would be something like that:

<div class="div">1</div>
<div class="div">2</div>
<div class="div">3</div>
<div class="div">4</div>
<div class="div">5</div>
<div>6</div>

jQuery(document).on('click', '.div', function() {
if ( $(this).is($(".div:last")) ) 
{
   console.log($(this))
}    
});

Link

You could either do that what you did, using the 'querySelector'

var lastElem = document.querySelector('div.class-name:last-child');

Or you could do something like this -

var elements = document.getElementsByClassName('class-name');
var lastElem = elements[elements.length - 1];

This is the standard query function, which accepts CSS selector syntax:

divs = document.querySelectorAll('.div');
last_div = divs.item(divs.length - 1);

See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM