There are certain cases when, we want to get the class of a particular element from multiple classes in that element, you can use the following code:
HTML:
<div id="gettingClass" class="firstClass secondClass">Click o the following button to get the first class and second class</div>
<button onclick="firstClass();">Class 1</button>
<button onclick="secondClass();">Class 2</button>
JS:
function firstClass(){
var old = document.getElementById('gettingClass');
var first_class = old.className.split(' ')[0]; // first class
console.log("First class is : "+first_class);
}
function secondClass(){
var old = document.getElementById('gettingClass');
var second_class = old.className.split(' ')[1]; // second class
console.log("Second class is : "+second_class);
}
You can also find the attached demo.
Please comment if you have any query.
0 Comment(s)