有人可以让我知道如何删除一个类的元素只使用JavaScript ? 请不要用jQuery给我一个答案,因为我不会用它,我对它一无所知。
当前回答
document.getElementById("whatever").className += "classToKeep";
使用加号('+')附加类,而不是覆盖任何现有的类
其他回答
我认为这很简单。
document.getElementById("whatever").classList.remove("className");
正确和标准的方法是使用classList。现在大多数现代浏览器的最新版本都广泛支持它:
ELEMENT.classList.remove("CLASS_NAME");
删除.点击 =() => { const el = document.querySelector('#el'); el.classList.remove(“red”); } .红色 { 背景:红色 } <div id='el' class=“red”> 测试</div> <按钮 id='删除'>删除类</button>
文档:https://developer.mozilla.org/en/DOM/element.classList
Edit
好的,完全重写。 已经有一段时间了,我学到了一些东西,评论也很有帮助。
Node.prototype.hasClass = function (className) {
if (this.classList) {
return this.classList.contains(className);
} else {
return (-1 < this.className.indexOf(className));
}
};
Node.prototype.addClass = function (className) {
if (this.classList) {
this.classList.add(className);
} else if (!this.hasClass(className)) {
var classes = this.className.split(" ");
classes.push(className);
this.className = classes.join(" ");
}
return this;
};
Node.prototype.removeClass = function (className) {
if (this.classList) {
this.classList.remove(className);
} else {
var classes = this.className.split(" ");
classes.splice(classes.indexOf(className), 1);
this.className = classes.join(" ");
}
return this;
};
旧邮政 我刚在用这样的东西。这是我想到的一个解决办法…
// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
Object.defineProperty(String.prototype,'trim', {
value: function() {
return this.replace(/^\s+|\s+$/g,'');
},
writable:false,
enumerable:false,
configurable:false
});
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
value: function(c) {
if(this.className.indexOf(c)<0) {
this.className=this.className+=' '+c;
}
return this;
},
writable:false,
enumerable:false,
configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
value: function(c) {
this.className=this.className.replace(c,'').replace(' ',' ').trim();
return this;
},
writable:false,
enumerable:false,
configurable:false
});
现在你可以调用myelement。removeclass ('myClass')
或者链它:myElement.removeClass("oldClass").addClass("newClass");
document.getElementById("whatever").className += "classToKeep";
使用加号('+')附加类,而不是覆盖任何现有的类
div.classList.add("foo");
div.classList.remove("foo");
更多信息请访问https://developer.mozilla.org/en-US/docs/Web/API/element.classList