javascript 仅当元素已经没有类时,如何将其添加到元素中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9515766/
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
How to add class to element only if it already does not have it?
提问by myWallJSON
How to add a class to an element only if it already does not have it? Say we don't know if the element has class="desired_class ...
but we want to make sure it has.
仅当元素已经没有类时,如何将其添加到元素中?假设我们不知道元素是否有,class="desired_class ...
但我们想确保它有。
采纳答案by dku.rajkumar
try this
试试这个
var elem = $('selector');
if(!elem.hasClass('desired_class')){
elem.addClass('desired_class');
}
回答by arnisritins
Also, you can use classList
property and it's add()
method:
此外,您可以使用classList
属性及其add()
方法:
var element = document.getElementById('myElement');
element.classList.add('myClass');
The class name will be added only if the element does not have it.
仅当元素没有类名时才会添加类名。
More about classList
:
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
更多关于classList
:https:
//developer.mozilla.org/en-US/docs/Web/API/Element/classList
回答by Steve Brush
I wrote a JavaScript-only function that checks if the class exists before adding it to the element. (You can always use classList
as mentioned here, but support for that starts with IE10.)
我编写了一个仅限 JavaScript 的函数,用于在将类添加到元素之前检查该类是否存在。(你总是可以classList
像这里提到的那样使用,但对它的支持从 IE10 开始。)
function addClass(name, element) {
var classesString;
classesString = element.className || "";
if (classesString.indexOf(name) === -1) {
element.className += " " + name;
}
}
var element = document.getElementById('some-element');
addClass("on", element); // Adds the class 'on'
addClass("on", element); // Ignored
addClass("on", element); // Ignored
document.write('Element classes: ' + element.className);
<div id="some-element"></div>
回答by Rajbir Sharma
In plain javascript check class existence by using below code. Here I'm checking el (element) has tempClass or not
使用下面的代码在普通的 javascript 检查类是否存在。在这里,我正在检查 el (element) 是否具有 tempClass
var el = document.getElementById("div1");
...
if (el.classList.contains("tempClass")){
return true;
}
回答by Pavan Andhukuri
Are you sure you want to do it with JQuery only? You can do it with simple JavaScript
你确定你只想用 JQuery 来做吗?你可以用简单的 JavaScript 做到
document.getElementById("elementId").getAttribute("class")
will give you null if the class attribute is not present.
如果 class 属性不存在,将为您提供 null 。
回答by Alex
if ($('element').hasClass('some_class')) {
$('element').addClass('class_name');
}
回答by Sudhir Bastakoti
if (!$("your_element").hasClass("desired_class")) {
$("your_element").addClass("desired_class");
}
回答by danboh
An updated answer to this question is using toggleClass
这个问题的更新答案是使用 toggleClass
$( "element" ).toggleClass( "className" );