仅使用 JavaScript 将 Remove Class 添加到 DOM 元素,以及这两种方法中的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14104881/
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
Add Remove Class to a DOM element using only JavaScript, and best of these 2 ways
提问by Premshankar Tiwari
What is a good approach to add class to a DOM element using JavaScript. And Remove also.
使用 JavaScript 将类添加到 DOM 元素的好方法是什么?并删除也。
I came across this following codes for adding:
我遇到了以下用于添加的代码:
1:
1:
Element.prototype.addClassName = function (cls) {
if (!this.hasClassName(cls)) {
this.className = [this.className, cls].join(" ");
}
};
2:
2:
document.querySelector(element).classList.add(cls)
Both of them seem to work for me. What is the difference between them and which is the best?
他们两个似乎都为我工作。它们之间有什么区别,哪个最好?
回答by Om Shankar
1. If you are moved by the word prototype, you might want to check MDN Docs - Inheritance and prototype chain.
1. 如果您被原型这个词所打动,您可能需要查看MDN Docs-Inheritance 和原型链。
2. The first code you mentioned is a normal cross-browser way of adding a class to an element.
Instead of being a function declaration, its added as a methodto the Element's prototype - so that when you query an Element by its id(good ol' JavaScript), you can simply call the method on the element itself.
2. 您提到的第一个代码是向元素添加类的正常跨浏览器方式。
它不是函数声明,而是作为方法添加到Element的原型中 - 这样当您通过其id(好的 JavaScript)查询 Element 时,您可以简单地在元素本身上调用该方法。
3. The second code you have posted is per the new DOM Specification. W3 Link. It will work only in those browsers that implement the DOM Level 4 Specs. It won't work in old browsers.
3. 您发布的第二个代码是根据新的 DOM 规范。W3 链接。它仅适用于实现 DOM Level 4 规范的浏览器。它在旧浏览器中不起作用。
That goes the difference.
这就是差异。
For the best method, a native method is always the best and fastest.
So for the browsers that support clasList, the second should be the best. Per my opinion though, till things (drafts) are not finalized you might want to consider a method that works cross-browser and is compatible with both JavaScript (ECMA-3) and supported DOM Spec.
对于最好的方法,本地方法总是最好和最快的。
所以对于支持 的浏览器,clasList第二种应该是最好的。不过,根据我的观点,在事情(草案)尚未最终确定之前,您可能需要考虑一种跨浏览器工作并且与 JavaScript (ECMA-3) 和受支持的 DOM 规范兼容的方法。
A simple idea should be to change the className, a property accessible in all new and old browsers, and append your classas a string to it:
一个简单的想法应该是更改className在所有新旧浏览器中都可以访问的属性,并将您的class作为字符串附加到它:
var el = document.getElementById(id);
el.className = el.className + " " + cls;
// mind the space while concatening
Of course you can add validation methods like using regexfor trimming spaces while adding and removing.
当然,您可以添加验证方法,例如regex用于在添加和删除时修剪空格。
By the way, I got the full part of the code you posted as the 1st Example:
顺便说一下,我得到了你作为第一个例子发布的代码的全部部分:
Element.prototype.hasClassName = function(name) {
return new RegExp("(?:^|\s+)" + name + "(?:\s+|$)").test(this.className);
};
Element.prototype.addClassName = function(name) {
if (!this.hasClassName(name)) {
this.className = this.className ? [this.className, name].join(' ') : name;
}
};
Element.prototype.removeClassName = function(name) {
if (this.hasClassName(name)) {
var c = this.className;
this.className = c.replace(new RegExp("(?:^|\s+)" + name + "(?:\s+|$)", "g"), "");
}
};
回答by Travis J
This is jquery's code.
这是jquery的代码。
Adapted versions of jQuery's addClass
And jQuery's removeClass
jQuery 的 addClass
和jQuery 的 removeClass 的改编版本
If you look at jQuery source code, this is how they do it. This is adapted from them, but pretty much entirely written by jQuery and is their code. I am not the original author, and am merely showing how one piece can be used instead of the whole library.
如果您查看 jQuery 源代码,就会发现他们是这样做的。这是从他们改编的,但几乎完全由 jQuery 编写并且是他们的代码。我不是原作者,只是展示如何使用一件作品而不是整个图书馆。
jQuery's addClass:
jQuery 的 addClass:
//This code is jQuery's
function AddClassToElement(elem,value){
var rspaces = /\s+/;
var classNames = (value || "").split( rspaces );
var className = " " + elem.className + " ",
setClass = elem.className;
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
}
}
elem.className = setClass.replace(/^\s+|\s+$/g,'');//trim
}
jQuery's removeClass:
jQuery 的 removeClass:
//This code is jQuery's
function RemoveClassFromElement(elem,value){
var rspaces = /\s+/;
var rclass = /[\n\t]/g
var classNames = (value || "").split( rspaces );
var className = (" " + elem.className + " ").replace(rclass, " ");
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[c] + " ", " ");
}
elem.className = className.replace(/^\s+|\s+$/g,'');//trim
}
Here is a working fiddle: http://jsfiddle.net/C5dvL/
这是一个工作小提琴:http: //jsfiddle.net/C5dvL/

