如何用普通的JavaScript来做jQuery的hasClass
?例如,
<body class="foo thatClass bar">
问<body>
是否有thatClass
的JavaScript方式是什么
发布于 2011-02-23 08:07:05
您可以检查element.className
是否与/\bthatClass\b/
匹配。
\b
匹配断字符。
或者,您可以使用jQuery自己的实现:
var className = " " + selector + " ";
if ( (" " + element.className + " ").replace(/[\n\t]/g, " ").indexOf(" thatClass ") > -1 )
要回答您更一般的问题,您可以查看github上的jQuery的source code或hasClass
specifically in this source viewer的源代码。
发布于 2015-02-25 07:45:27
// 1. Use if for see that classes:
if (document.querySelector(".section-name").classList.contains("section-filter")) {
alert("Grid section");
// code...
}
<!--2. Add a class in the .html:-->
<div class="section-name section-filter">...</div>
发布于 2011-02-23 08:11:03
存储正在使用的类的属性是className
。
所以你可以说:
if (document.body.className.match(/\bmyclass\b/)) {
....
}
如果你想要一个向你展示jQuery如何做每件事的位置,我建议:
https://stackoverflow.com/questions/5085567
复制相似问题