检查元素是否具有类的最佳方式是什么? [英] What is the best way to check if element has a class?

查看:99
本文介绍了检查元素是否具有类的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果元素有多个类,那么它将不匹配常规属性值检查,所以我正在寻找最好的方法来检查是否该对象在该元素的className属性中具有特定的类。

If the element has multiple classes then it will not match with the regular property value checking, so I'm looking for the best way to check if the object has a particular class in the element's className property.

// element's classname is 'hello world helloworld'
var element = document.getElementById('element');

// this obviously fails
if(element.className == 'hello'){ ... }

// this is not good if the className is just 'helloworld' because it will match
if(element.className.indexOf('hello') != -1){ ... }  

那么最好的方法是什么?

So what would be the best way to do this?

只是纯粹的javascript请

推荐答案

function hasClass( elem, klass ) {
     return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}

这篇关于检查元素是否具有类的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆