I have an element that already has a class:
我有一个元素已经有一个类:
<div class="someclass">
<img ... id="image1" name="image1" />
</div>
Now I want to create a Javascript function that will add a class to the div
(not replace, but add).
现在我想创建一个Javascript函数,它将向div添加一个类(不是替换,而是添加)。
How can I do that?
我怎么做呢?
23 个解决方案
#1
1618
Add a space plus the name of your new class to the className
property of the element. First, put an id
on the element so you can easily get a reference.
在元素的className属性中添加一个空格加上新类的名称。首先,在元素上放一个id,这样您就可以轻松地获得引用。
<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
Then
然后
var d = document.getElementById("div1");
d.className += " otherclass";
See also element.className on MDN.
参见元素。名称中数。
#2
1002
The easiest way to do this without any framework is to use element.classList.add method.
没有任何框架的最简单的方法是使用element.classList。添加方法。
var element = document.getElementById("div1");
element.classList.add("otherclass");
Edit: And if you want to remove class from an element -
编辑:如果你想从元素中删除类-
element.classList.remove("otherclass");
I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the document.className
approach). There are some browser limitations, but you can work around them using polyfills.
我不希望自己添加任何空空间和重复条目(这是使用文档时需要的)。名称的方法)。浏览器有一些限制,但是您可以使用polyfill来解决它们。
#3
170
find your target element "d" however you wish and then:
找到你的目标元素“d”,然后:
d.className += ' additionalClass'; //note the space
you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..
你可以用更巧妙的方式把它包装起来,以检查是否存在,以及空间需求等等。
#4
114
Add Class
-
Cross Compatible
交叉兼容
In the following example we add a
classname
to the<body>
element. This is IE-8 compatible.在下面的示例中,我们向元素添加一个类名。这是ie 8兼容。
var a = document.body; a.classList ? a.classList.add('classname') : a.className += ' classname';
This is shorthand for the following..
这是对下列事物的简写。
var a = document.body; if (a.classList) { a.classList.add('wait'); } else { a.className += ' wait'; }
-
Performance
性能
If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster.
如果您更关心跨兼容性的性能,您可以将其缩短为以下的4%。
var z = document.body; document.body.classList.add('wait');
-
Convenience
方便
Alternatively you could use jQuery but the resulting performance is significantly slower. 94% slower according to jsPerf
您也可以使用jQuery,但结果的性能要慢得多。根据jsPerf的数据,慢94%
$('body').addClass('wait');
Removing the class
-
Performance
性能
Using jQuery selectively is the best method for removing a class if your concerned with performance
如果您关心性能,那么选择使用jQuery是删除类的最佳方法
var a = document.body, c = ' classname'; $(a).removeClass(c);
-
Without jQuery it's 32% slower
如果没有jQuery,速度会慢32%
var a = document.body, c = ' classname'; a.className = a.className.replace( c, '' ); a.className = a.className + c;
References
- jsPerf Test Case: Adding a Class
- jsPerf测试用例:添加类
- jsPerf Test Case: Removing a Class
- jsPerf测试用例:删除类
Using Prototype
Element("document.body").ClassNames.add("classname")
Element("document.body").ClassNames.remove("classname")
Element("document.body").ClassNames.set("classname")
Using YUI
YAHOO.util.Dom.hasClass(document.body,"classname")
YAHOO.util.Dom.addClass(document.body,"classname")
YAHOO.util.Dom.removeClass(document.body,"classname")
#5
32
Another approach to add the class to element using pure JavaScript
另一种使用纯JavaScript将类添加到元素的方法
For adding class:
添加类:
document.getElementById("div1").classList.add("classToBeAdded");
For removing class:
删除类:
document.getElementById("div1").classList.remove("classToBeRemoved");
#6
20
When the work I'm doing doesn't warrant using a library, I use these two functions:
当我做的工作不需要使用图书馆时,我使用这两个功能:
function addClass( classname, element ) {
var cn = element.className;
//test for existance
if( cn.indexOf( classname ) != -1 ) {
return;
}
//add a space if the element already has class
if( cn != '' ) {
classname = ' '+classname;
}
element.className = cn+classname;
}
function removeClass( classname, element ) {
var cn = element.className;
var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
cn = cn.replace( rxp, '' );
element.className = cn;
}
#7
19
Assuming you're doing more than just adding this one class (eg, you've got asynchronous requests and so on going on as well), I'd recommend a library like Prototype or jQuery.
假设您所做的不仅仅是添加这个类(例如,您有异步请求等等),我建议您使用Prototype或jQuery之类的库。
This will make just about everything you'll need to do (including this) very simple.
这将使您需要做的几乎所有事情(包括此事项)都非常简单。
So let's say you've got jQuery on your page now, you could use code like this to add a class name to an element (on load, in this case):
假设你的页面上有jQuery,你可以使用如下代码向一个元素添加一个类名(在本例中是on load):
$(document).ready( function() {
$('#div1').addClass( 'some_other_class' );
} );
Check out the jQuery API browser for other stuff.
查看jQuery API浏览器了解其他内容。
#8
15
You can use the classList.add OR classList.remove method to add/remove a class from a element.
您可以使用类列表。添加或班级名册。删除从元素中添加/删除类的方法。
var nameElem = document.getElementById("name")
nameElem.classList.add("anyclss")
The above code will add(and NOT replace) a class "anyclass" to nameElem. Similarly you can use classList.remove() method to remove a class.
上面的代码将向nameElem添加(而不是替换)一个类“anyclass”。类似地,您可以使用classList.remove()方法来删除类。
nameElem.classList.remove("anyclss")
#9
9
To add an additional class to an element:
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:
要向元素中添加类,而不删除/影响现有值,请附加一个空格和新的类名,如下所示:
document.getElementById("MyElement").className += " MyClass";
To change all classes for an element:
To replace all existing classes with one or more new classes, set the className attribute:
要用一个或多个新类替换所有现有的类,请设置className属性:
document.getElementById("MyElement").className = "MyClass";
(You can use a space-delimited list to apply multiple classes.)
(您可以使用空格分隔的列表来应用多个类。)
#10
4
Just to elaborate on what others have said, multiple CSS classes are combined in a single string, delimited by spaces. Thus, if you wanted to hard-code it, it would simply look like this:
为了说明其他人所说的,多个CSS类被组合在一个字符串中,由空格分隔。因此,如果您想对它进行硬编码,只需如下所示:
<div class="someClass otherClass yetAnotherClass">
<img ... id="image1" name="image1" />
</div>
From there you can easily derive the javascript necessary to add a new class... just append a space followed by the new class to the element's className property. Knowing this, you can also write a function to remove a class later should the need arise.
从那里,您可以轻松地派生添加新类所需的javascript……只需在元素的className属性后面添加一个空格。了解了这一点之后,您还可以编写一个函数,以便在需要时删除类。
#11
4
To add, remove or check element classes in a simple way:
以简单的方式添加、删除或检查元素类:
var uclass = {
exists: function(elem,className){var p = new RegExp('(^| )'+className+'( |$)');return (elem.className && elem.className.match(p));},
add: function(elem,className){if(uclass.exists(elem,className)){return true;}elem.className += ' '+className;},
remove: function(elem,className){var c = elem.className;var p = new RegExp('(^| )'+className+'( |$)');c = c.replace(p,' ').replace(/ /g,' ');elem.className = c;}
};
var elem = document.getElementById('someElem');
//Add a class, only if not exists yet.
uclass.add(elem,'someClass');
//Remove class
uclass.remove(elem,'someClass');
#12
4
If you don't want to use jQuery and want to support older browsers:
如果你不想使用jQuery,想要支持旧浏览器:
function addClass(elem, clazz) {
if (!elemHasClass(elem, clazz)) {
elem.className += " " + clazz;
}
}
function elemHasClass(elem, clazz) {
return new RegExp("( |^)" + clazz + "( |$)").test(elem.className);
}
#13
4
I know IE9 is shutdown officially and we can achieve it with element.classList
as many told above but I just tried to learn how it works without classList
with help of many answers above I could learn it.
我知道IE9已经正式关闭,我们可以用元素来实现。正如上面所讲的一样,我只是试着在没有课表的帮助下学习它是如何工作的。
Below code extends many answers above and improves them by avoiding adding duplicate classes.
下面的代码扩展了上面的许多答案,并通过避免添加重复类来改进它们。
function addClass(element,className){
var classArray = className.split(' ');
classArray.forEach(function (className) {
if(!hasClass(element,className)){
element.className += " "+className;
}
});
}
//this will add 5 only once
addClass(document.querySelector('#getbyid'),'3 4 5 5 5');
#14
2
Sample with pure JS. In first example we get our element's id and add e.g. 2 classes.
样品与纯JS。在第一个例子中,我们得到元素的id并添加两个类。
document.addEventListener('DOMContentLoaded', function() {
document.getElementsById('tabGroup').className = "anyClass1 anyClass2";
})
In second example we get element's class name and add 1 more.
在第二个示例中,我们获取元素的类名并添加1。
document.addEventListener('DOMContentLoaded', function() {
document.getElementsByClassName('tabGroup')[0].className = "tabGroup ready";
})
#15
2
I think it's better to use pure JavaScript, which we can run on the DOM of the Browser.
我认为最好使用纯JavaScript,我们可以在浏览器的DOM上运行它。
Here is the functional way to use it. I have used ES6 but feel free to use ES5 and function expression or function definition, whichever suits your JavaScript StyleGuide.
这里是使用它的功能方式。我使用过ES6,但是可以随意使用ES5和函数表达式或函数定义,以适合您的JavaScript样式指南。
'use strict'
const oldAdd = (element, className) => {
let classes = element.className.split(' ')
if (classes.indexOf(className) < 0) {
classes.push(className)
}
element.className = classes.join(' ')
}
const oldRemove = (element, className) => {
let classes = element.className.split(' ')
const idx = classes.indexOf(className)
if (idx > -1) {
classes.splice(idx, 1)
}
element.className = classes.join(' ')
}
const addClass = (element, className) => {
if (element.classList) {
element.classList.add(className)
} else {
oldAdd(element, className)
}
}
const removeClass = (element, className) => {
if (element.classList) {
element.classList.remove(className)
} else {
oldRemove(element, className)
}
}
#16
2
You can use modern approach similar to jQuery
您可以使用类似于jQuery的现代方法
If you need to change only one element, first one that JS will find in DOM, you can use this:
如果您只需要更改一个元素,首先JS将在DOM中找到,您可以使用以下方法:
document.querySelector('.someclass').className += " red";
.red {
color: red;
}
<div class="someclass">
<p>This method will add class "red" only to first element in DOM</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
Keep in mind to leave one space before class name.
记住在类名之前要留一个空格。
If you have multiple classes where you want to add new class, you can use it like this
如果有多个类需要添加新类,可以这样使用它
document.querySelectorAll('.someclass').forEach(function(element) {
element.className += " red";
});
.red {
color: red;
}
<div class="someclass">
<p>This method will add class "red" to all elements in DOM that have "someclass" class.</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
#17
1
I too think that the fastest way is to use Element.prototype.classList as in es5: document.querySelector(".my.super-class").classList.add('new-class')
but in ie8 there is no such thing as Element.prototype.classList, anyway you can polyfill it with this snippet (fell free to edit and improve it):
我也认为最快的方法是使用Element.prototype。类列表,如es5: document.querySelector(".my.super-class").classList.add('new-class'),但在ie8中没有Element.prototype这样的东西。classList,无论如何你可以用这段代码填充它(可以*地编辑和改进它):
if(Element.prototype.classList === void 0){
function DOMTokenList(classes, self){
typeof classes == "string" && (classes = classes.split(' '))
while(this.length){
Array.prototype.pop.apply(this);
}
Array.prototype.push.apply(this, classes);
this.__self__ = this.__self__ || self
}
DOMTokenList.prototype.item = function (index){
return this[index];
}
DOMTokenList.prototype.contains = function (myClass){
for(var i = this.length - 1; i >= 0 ; i--){
if(this[i] === myClass){
return true;
}
}
return false
}
DOMTokenList.prototype.add = function (newClass){
if(this.contains(newClass)){
return;
}
this.__self__.className += (this.__self__.className?" ":"")+newClass;
DOMTokenList.call(this, this.__self__.className)
}
DOMTokenList.prototype.remove = function (oldClass){
if(!this.contains(newClass)){
return;
}
this[this.indexOf(oldClass)] = undefined
this.__self__.className = this.join(' ').replace(/ +/, ' ')
DOMTokenList.call(this, this.__self__.className)
}
DOMTokenList.prototype.toggle = function (aClass){
this[this.contains(aClass)? 'remove' : 'add'](aClass)
return this.contains(aClass);
}
DOMTokenList.prototype.replace = function (oldClass, newClass){
this.contains(oldClass) && this.remove(oldClass) && this.add(newClass)
}
Object.defineProperty(Element.prototype, 'classList', {
get: function() {
return new DOMTokenList( this.className, this );
},
enumerable: false
})
}
#18
0
first, give the div an id. Then, call function appendClass:
首先给div一个id,然后调用函数appendClass:
<script language="javascript">
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAdd) == -1)
{
document.getElementById(elementId).setAttribute("class", classToAppend);
}
}
</script>
#19
0
You can use the API querySelector to select your element and then create a function with the element and the new classname as parameters. Using classlist for modern browsers, else for IE8. Then you can call the function after an event.
您可以使用API querySelector选择元素,然后使用元素和新的classname作为参数创建一个函数。为现代浏览器使用classlist,为IE8使用else。然后可以在事件之后调用函数。
//select the dom element
var addClassVar = document.querySelector('.someclass');
//define the addclass function
var addClass = function(el,className){
if (el.classList){
el.classList.add(className);
}
else {
el.className += ' ' + className;
}
};
//call the function
addClass(addClassVar, 'newClass');
#20
0
For those using Lodash and wanting to update className
string:
对于那些使用Lodash并希望更新className字符串的用户:
// get element reference
var elem = document.getElementById('myElement');
// add some classes. Eg. 'nav' and 'nav header'
elem.className = _.chain(elem.className).split(/[\s]+/).union(['nav','navHeader']).join(' ').value()
// remove the added classes
elem.className = _.chain(elem.className).split(/[\s]+/).difference(['nav','navHeader']).join(' ').value()
#21
-4
This js code works for me
这个js代码适合我
provides classname replacement
提供名称替换
var DDCdiv = hEle.getElementBy.....
var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array
for (var i=0; i< Ta.length;i++)
{
if (Ta[i] == 'visible'){
Ta[i] = 'hidden';
break;// quit for loop
}
else if (Ta[i] == 'hidden'){
Ta[i] = 'visible';
break;// quit for loop
}
}
DDCdiv.setAttribute('class',Ta.join(' ') ); // Join array with space and set class name
To add just use
添加用
var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array
Ta.push('New class name');
// Ta.push('Another class name');//etc...
DDCdiv.setAttribute('class',Ta.join(' ') ); // Join array with space and set class name
To remove use
删除使用
var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array
for (var i=0; i< Ta.length;i++)
{
if (Ta[i] == 'visible'){
Ta.splice( i, 1 );
break;// quit for loop
}
}
DDCdiv.setAttribute('class',Ta.join(' ') ); // Join array with space and set class name
Hope this is helpful to sombody
希望这对身体有帮助。
#22
-9
In YUI, if you include yuidom, you can use
在YUI中,如果包含yuidom,可以使用
YAHOO.util.Dom.addClass('div1','className');
YAHOO.util.Dom.addClass(“div1”、“名称”);
HTH
HTH
#23
-10
function toggleClass (El) {
if (El.className != "white") {
El.className = "white"
}
else{
El.className = "black";
};
}
this will toggle the class you want to toggle without jQuery
这将切换不使用jQuery的类
#1
1618
Add a space plus the name of your new class to the className
property of the element. First, put an id
on the element so you can easily get a reference.
在元素的className属性中添加一个空格加上新类的名称。首先,在元素上放一个id,这样您就可以轻松地获得引用。
<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
Then
然后
var d = document.getElementById("div1");
d.className += " otherclass";
See also element.className on MDN.
参见元素。名称中数。
#2
1002
The easiest way to do this without any framework is to use element.classList.add method.
没有任何框架的最简单的方法是使用element.classList。添加方法。
var element = document.getElementById("div1");
element.classList.add("otherclass");
Edit: And if you want to remove class from an element -
编辑:如果你想从元素中删除类-
element.classList.remove("otherclass");
I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the document.className
approach). There are some browser limitations, but you can work around them using polyfills.
我不希望自己添加任何空空间和重复条目(这是使用文档时需要的)。名称的方法)。浏览器有一些限制,但是您可以使用polyfill来解决它们。
#3
170
find your target element "d" however you wish and then:
找到你的目标元素“d”,然后:
d.className += ' additionalClass'; //note the space
you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..
你可以用更巧妙的方式把它包装起来,以检查是否存在,以及空间需求等等。
#4
114
Add Class
-
Cross Compatible
交叉兼容
In the following example we add a
classname
to the<body>
element. This is IE-8 compatible.在下面的示例中,我们向元素添加一个类名。这是ie 8兼容。
var a = document.body; a.classList ? a.classList.add('classname') : a.className += ' classname';
This is shorthand for the following..
这是对下列事物的简写。
var a = document.body; if (a.classList) { a.classList.add('wait'); } else { a.className += ' wait'; }
-
Performance
性能
If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster.
如果您更关心跨兼容性的性能,您可以将其缩短为以下的4%。
var z = document.body; document.body.classList.add('wait');
-
Convenience
方便
Alternatively you could use jQuery but the resulting performance is significantly slower. 94% slower according to jsPerf
您也可以使用jQuery,但结果的性能要慢得多。根据jsPerf的数据,慢94%
$('body').addClass('wait');
Removing the class
-
Performance
性能
Using jQuery selectively is the best method for removing a class if your concerned with performance
如果您关心性能,那么选择使用jQuery是删除类的最佳方法
var a = document.body, c = ' classname'; $(a).removeClass(c);
-
Without jQuery it's 32% slower
如果没有jQuery,速度会慢32%
var a = document.body, c = ' classname'; a.className = a.className.replace( c, '' ); a.className = a.className + c;
References
- jsPerf Test Case: Adding a Class
- jsPerf测试用例:添加类
- jsPerf Test Case: Removing a Class
- jsPerf测试用例:删除类
Using Prototype
Element("document.body").ClassNames.add("classname")
Element("document.body").ClassNames.remove("classname")
Element("document.body").ClassNames.set("classname")
Using YUI
YAHOO.util.Dom.hasClass(document.body,"classname")
YAHOO.util.Dom.addClass(document.body,"classname")
YAHOO.util.Dom.removeClass(document.body,"classname")
#5
32
Another approach to add the class to element using pure JavaScript
另一种使用纯JavaScript将类添加到元素的方法
For adding class:
添加类:
document.getElementById("div1").classList.add("classToBeAdded");
For removing class:
删除类:
document.getElementById("div1").classList.remove("classToBeRemoved");
#6
20
When the work I'm doing doesn't warrant using a library, I use these two functions:
当我做的工作不需要使用图书馆时,我使用这两个功能:
function addClass( classname, element ) {
var cn = element.className;
//test for existance
if( cn.indexOf( classname ) != -1 ) {
return;
}
//add a space if the element already has class
if( cn != '' ) {
classname = ' '+classname;
}
element.className = cn+classname;
}
function removeClass( classname, element ) {
var cn = element.className;
var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
cn = cn.replace( rxp, '' );
element.className = cn;
}
#7
19
Assuming you're doing more than just adding this one class (eg, you've got asynchronous requests and so on going on as well), I'd recommend a library like Prototype or jQuery.
假设您所做的不仅仅是添加这个类(例如,您有异步请求等等),我建议您使用Prototype或jQuery之类的库。
This will make just about everything you'll need to do (including this) very simple.
这将使您需要做的几乎所有事情(包括此事项)都非常简单。
So let's say you've got jQuery on your page now, you could use code like this to add a class name to an element (on load, in this case):
假设你的页面上有jQuery,你可以使用如下代码向一个元素添加一个类名(在本例中是on load):
$(document).ready( function() {
$('#div1').addClass( 'some_other_class' );
} );
Check out the jQuery API browser for other stuff.
查看jQuery API浏览器了解其他内容。
#8
15
You can use the classList.add OR classList.remove method to add/remove a class from a element.
您可以使用类列表。添加或班级名册。删除从元素中添加/删除类的方法。
var nameElem = document.getElementById("name")
nameElem.classList.add("anyclss")
The above code will add(and NOT replace) a class "anyclass" to nameElem. Similarly you can use classList.remove() method to remove a class.
上面的代码将向nameElem添加(而不是替换)一个类“anyclass”。类似地,您可以使用classList.remove()方法来删除类。
nameElem.classList.remove("anyclss")
#9
9
To add an additional class to an element:
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:
要向元素中添加类,而不删除/影响现有值,请附加一个空格和新的类名,如下所示:
document.getElementById("MyElement").className += " MyClass";
To change all classes for an element:
To replace all existing classes with one or more new classes, set the className attribute:
要用一个或多个新类替换所有现有的类,请设置className属性:
document.getElementById("MyElement").className = "MyClass";
(You can use a space-delimited list to apply multiple classes.)
(您可以使用空格分隔的列表来应用多个类。)
#10
4
Just to elaborate on what others have said, multiple CSS classes are combined in a single string, delimited by spaces. Thus, if you wanted to hard-code it, it would simply look like this:
为了说明其他人所说的,多个CSS类被组合在一个字符串中,由空格分隔。因此,如果您想对它进行硬编码,只需如下所示:
<div class="someClass otherClass yetAnotherClass">
<img ... id="image1" name="image1" />
</div>
From there you can easily derive the javascript necessary to add a new class... just append a space followed by the new class to the element's className property. Knowing this, you can also write a function to remove a class later should the need arise.
从那里,您可以轻松地派生添加新类所需的javascript……只需在元素的className属性后面添加一个空格。了解了这一点之后,您还可以编写一个函数,以便在需要时删除类。
#11
4
To add, remove or check element classes in a simple way:
以简单的方式添加、删除或检查元素类:
var uclass = {
exists: function(elem,className){var p = new RegExp('(^| )'+className+'( |$)');return (elem.className && elem.className.match(p));},
add: function(elem,className){if(uclass.exists(elem,className)){return true;}elem.className += ' '+className;},
remove: function(elem,className){var c = elem.className;var p = new RegExp('(^| )'+className+'( |$)');c = c.replace(p,' ').replace(/ /g,' ');elem.className = c;}
};
var elem = document.getElementById('someElem');
//Add a class, only if not exists yet.
uclass.add(elem,'someClass');
//Remove class
uclass.remove(elem,'someClass');
#12
4
If you don't want to use jQuery and want to support older browsers:
如果你不想使用jQuery,想要支持旧浏览器:
function addClass(elem, clazz) {
if (!elemHasClass(elem, clazz)) {
elem.className += " " + clazz;
}
}
function elemHasClass(elem, clazz) {
return new RegExp("( |^)" + clazz + "( |$)").test(elem.className);
}
#13
4
I know IE9 is shutdown officially and we can achieve it with element.classList
as many told above but I just tried to learn how it works without classList
with help of many answers above I could learn it.
我知道IE9已经正式关闭,我们可以用元素来实现。正如上面所讲的一样,我只是试着在没有课表的帮助下学习它是如何工作的。
Below code extends many answers above and improves them by avoiding adding duplicate classes.
下面的代码扩展了上面的许多答案,并通过避免添加重复类来改进它们。
function addClass(element,className){
var classArray = className.split(' ');
classArray.forEach(function (className) {
if(!hasClass(element,className)){
element.className += " "+className;
}
});
}
//this will add 5 only once
addClass(document.querySelector('#getbyid'),'3 4 5 5 5');
#14
2
Sample with pure JS. In first example we get our element's id and add e.g. 2 classes.
样品与纯JS。在第一个例子中,我们得到元素的id并添加两个类。
document.addEventListener('DOMContentLoaded', function() {
document.getElementsById('tabGroup').className = "anyClass1 anyClass2";
})
In second example we get element's class name and add 1 more.
在第二个示例中,我们获取元素的类名并添加1。
document.addEventListener('DOMContentLoaded', function() {
document.getElementsByClassName('tabGroup')[0].className = "tabGroup ready";
})
#15
2
I think it's better to use pure JavaScript, which we can run on the DOM of the Browser.
我认为最好使用纯JavaScript,我们可以在浏览器的DOM上运行它。
Here is the functional way to use it. I have used ES6 but feel free to use ES5 and function expression or function definition, whichever suits your JavaScript StyleGuide.
这里是使用它的功能方式。我使用过ES6,但是可以随意使用ES5和函数表达式或函数定义,以适合您的JavaScript样式指南。
'use strict'
const oldAdd = (element, className) => {
let classes = element.className.split(' ')
if (classes.indexOf(className) < 0) {
classes.push(className)
}
element.className = classes.join(' ')
}
const oldRemove = (element, className) => {
let classes = element.className.split(' ')
const idx = classes.indexOf(className)
if (idx > -1) {
classes.splice(idx, 1)
}
element.className = classes.join(' ')
}
const addClass = (element, className) => {
if (element.classList) {
element.classList.add(className)
} else {
oldAdd(element, className)
}
}
const removeClass = (element, className) => {
if (element.classList) {
element.classList.remove(className)
} else {
oldRemove(element, className)
}
}
#16
2
You can use modern approach similar to jQuery
您可以使用类似于jQuery的现代方法
If you need to change only one element, first one that JS will find in DOM, you can use this:
如果您只需要更改一个元素,首先JS将在DOM中找到,您可以使用以下方法:
document.querySelector('.someclass').className += " red";
.red {
color: red;
}
<div class="someclass">
<p>This method will add class "red" only to first element in DOM</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
Keep in mind to leave one space before class name.
记住在类名之前要留一个空格。
If you have multiple classes where you want to add new class, you can use it like this
如果有多个类需要添加新类,可以这样使用它
document.querySelectorAll('.someclass').forEach(function(element) {
element.className += " red";
});
.red {
color: red;
}
<div class="someclass">
<p>This method will add class "red" to all elements in DOM that have "someclass" class.</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
<div class="someclass">
<p>lorem ipsum</p>
</div>
#17
1
I too think that the fastest way is to use Element.prototype.classList as in es5: document.querySelector(".my.super-class").classList.add('new-class')
but in ie8 there is no such thing as Element.prototype.classList, anyway you can polyfill it with this snippet (fell free to edit and improve it):
我也认为最快的方法是使用Element.prototype。类列表,如es5: document.querySelector(".my.super-class").classList.add('new-class'),但在ie8中没有Element.prototype这样的东西。classList,无论如何你可以用这段代码填充它(可以*地编辑和改进它):
if(Element.prototype.classList === void 0){
function DOMTokenList(classes, self){
typeof classes == "string" && (classes = classes.split(' '))
while(this.length){
Array.prototype.pop.apply(this);
}
Array.prototype.push.apply(this, classes);
this.__self__ = this.__self__ || self
}
DOMTokenList.prototype.item = function (index){
return this[index];
}
DOMTokenList.prototype.contains = function (myClass){
for(var i = this.length - 1; i >= 0 ; i--){
if(this[i] === myClass){
return true;
}
}
return false
}
DOMTokenList.prototype.add = function (newClass){
if(this.contains(newClass)){
return;
}
this.__self__.className += (this.__self__.className?" ":"")+newClass;
DOMTokenList.call(this, this.__self__.className)
}
DOMTokenList.prototype.remove = function (oldClass){
if(!this.contains(newClass)){
return;
}
this[this.indexOf(oldClass)] = undefined
this.__self__.className = this.join(' ').replace(/ +/, ' ')
DOMTokenList.call(this, this.__self__.className)
}
DOMTokenList.prototype.toggle = function (aClass){
this[this.contains(aClass)? 'remove' : 'add'](aClass)
return this.contains(aClass);
}
DOMTokenList.prototype.replace = function (oldClass, newClass){
this.contains(oldClass) && this.remove(oldClass) && this.add(newClass)
}
Object.defineProperty(Element.prototype, 'classList', {
get: function() {
return new DOMTokenList( this.className, this );
},
enumerable: false
})
}
#18
0
first, give the div an id. Then, call function appendClass:
首先给div一个id,然后调用函数appendClass:
<script language="javascript">
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAdd) == -1)
{
document.getElementById(elementId).setAttribute("class", classToAppend);
}
}
</script>
#19
0
You can use the API querySelector to select your element and then create a function with the element and the new classname as parameters. Using classlist for modern browsers, else for IE8. Then you can call the function after an event.
您可以使用API querySelector选择元素,然后使用元素和新的classname作为参数创建一个函数。为现代浏览器使用classlist,为IE8使用else。然后可以在事件之后调用函数。
//select the dom element
var addClassVar = document.querySelector('.someclass');
//define the addclass function
var addClass = function(el,className){
if (el.classList){
el.classList.add(className);
}
else {
el.className += ' ' + className;
}
};
//call the function
addClass(addClassVar, 'newClass');
#20
0
For those using Lodash and wanting to update className
string:
对于那些使用Lodash并希望更新className字符串的用户:
// get element reference
var elem = document.getElementById('myElement');
// add some classes. Eg. 'nav' and 'nav header'
elem.className = _.chain(elem.className).split(/[\s]+/).union(['nav','navHeader']).join(' ').value()
// remove the added classes
elem.className = _.chain(elem.className).split(/[\s]+/).difference(['nav','navHeader']).join(' ').value()
#21
-4
This js code works for me
这个js代码适合我
provides classname replacement
提供名称替换
var DDCdiv = hEle.getElementBy.....
var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array
for (var i=0; i< Ta.length;i++)
{
if (Ta[i] == 'visible'){
Ta[i] = 'hidden';
break;// quit for loop
}
else if (Ta[i] == 'hidden'){
Ta[i] = 'visible';
break;// quit for loop
}
}
DDCdiv.setAttribute('class',Ta.join(' ') ); // Join array with space and set class name
To add just use
添加用
var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array
Ta.push('New class name');
// Ta.push('Another class name');//etc...
DDCdiv.setAttribute('class',Ta.join(' ') ); // Join array with space and set class name
To remove use
删除使用
var cssCNs = DDCdiv.getAttribute('class');
var Ta = cssCNs.split(' '); //split into an array
for (var i=0; i< Ta.length;i++)
{
if (Ta[i] == 'visible'){
Ta.splice( i, 1 );
break;// quit for loop
}
}
DDCdiv.setAttribute('class',Ta.join(' ') ); // Join array with space and set class name
Hope this is helpful to sombody
希望这对身体有帮助。
#22
-9
In YUI, if you include yuidom, you can use
在YUI中,如果包含yuidom,可以使用
YAHOO.util.Dom.addClass('div1','className');
YAHOO.util.Dom.addClass(“div1”、“名称”);
HTH
HTH
#23
-10
function toggleClass (El) {
if (El.className != "white") {
El.className = "white"
}
else{
El.className = "black";
};
}
this will toggle the class you want to toggle without jQuery
这将切换不使用jQuery的类