Search code examples
javascripthtmlclassdom-eventsclassname

Get only first class of an HTML element


I'm using the

event.target.className

to get the ClassName, but sometimes an element has multiple class names, how can I make it, so it only gives the first class name as outcome?

Oh, and please without jQuery.


Solution

  • There are various ways to get first class of an element

    Method first : Using className property

    Using the className property of DOM elements with the split function which will split className by spaces and return an array.

    event.target.className.split(" ")[0]; //0 to retrieve first class
    

    The className property is supported in all major browsers.

    Method second : Using classList property

    Using the classList property of DOM elements which return a DOMTokenList Object of classes(already split by space)

    event.target.classList[0]; //0 to retrieve first class
    

    The classList property is relatively new and relatively faster too. This is not supported in IE8 and IE9. Support in various browsers

    Check performance of classList vs className