Javascript 仅获取 HTML 元素的第一类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11606897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get only first class of an HTML element
提问by bugwheels94
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 onlygives the first classname as outcome?
我正在使用 event.target.className 来获取 ClassName,但有时一个元素有多个类名,我该如何制作它,所以它只给出第一个类名作为结果?
Oh, and please without jQuery.
哦,请不要使用 jQuery。
回答by bugwheels94
There are various ways to get first class of an element
有多种方法可以获取元素的第一类
Method first: Using className property
方法一:使用 className 属性
Using the className property of DOM elements with the split function which will split className by spaces and return an array.
将 DOM 元素的 className 属性与 split 函数一起使用,该函数将按空格拆分 className 并返回一个数组。
event.target.className.split(" ")[0]; //0 to retrieve first class
The className property is supported in all major browsers.
所有主要浏览器都支持 className 属性。
Method second: Using classList property
方法二:使用 classList 属性
Using the classList property of DOM elements which return a DOMTokenListObject of classes(already split by space)
使用返回类的DOMTokenList对象的 DOM 元素的 classList 属性(已按空间分割)
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
classList 属性相对较新,速度也相对较快。这在 IE8 和 IE9 中不受支持。支持各种浏览器