KOMPX.COM or COMPMISCELLANEA.COM   

Getting the last class name in classList collection

Getting the last class name out of Element.classList collection. Vanilla JavaScript.

Example:

An element has three class names: example, example2, example3. The script gets the last class name and prints it inside the div:

HTML code:


<div class="example example2 example3">
</div>

JavaScript code:


<script>
// Getting the last class name
var lastClassName = document.querySelector('.example').classList[ document.querySelector('.example').classList.length-1 ];

// Printing the last class name
document.querySelector('.example').textContent = lastClassName;
</script>

Browser support
Windows
Internet Explorer 10.0+
Edge 12.0+
Firefox 3.6+
Google Chrome 8.0+
Opera 11.5+
Safari 5.1+
Linux
Firefox 3.6+
Google Chrome / Chromium
Opera 11.5+
More