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
- Accessing the first element in forEach loop (JavaScript)
- Adding a class to all sibling elements of a specific type in JavaScript
- Append an element after a specific element in JavaScript
- Array to string in JavaScript
- Calculate sum of HTML table column in JavaScript
- Detecting a newly generated element and adding a class to it in JavaScript
- Detect if a class has been added (JavaScript)
- Generating an HTML list out of page headings in JavaScript
- Get the current URL in JavaScript
- Remove all attributes of an element
- Removing the last character from a string in Javascript
- Transliterating Russian to English in JavaScript
- Wrap each character of a string in <span> tag (JavaScript)
- Wrap each word of text in <span> tag (JavaScript)