Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  160] [ 3]  / answers: 1 / hits: 35231  / 12 Years ago, mon, july 23, 2012, 12:00:00

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.


More From » html

 Answers
147

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


[#84088] Saturday, July 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martina

Total Points: 101
Total Questions: 103
Total Answers: 111

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;