Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to get the first class from multiple class of an element using js with demo

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 482
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: