How can assign multiple css classes to an html element through javascript withou开发者_JAVA百科t using any libraries?
Here's a simpler method to add multiple classes via classList
(supported by all modern browsers, as noted in other answers here):
div.classList.add('foo', 'bar'); // add multiple classes
From: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples
If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add()
via this one-liner:
let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);
Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like @LayZee's above.
Try doing this...
document.getElementById("MyElement").className += " MyClass";
Got this here...
This works:
myElement.className = 'foo bar baz';
There are at least a few different ways:
var buttonTop = document.getElementById("buttonTop");
buttonTop.className = "myElement myButton myStyle";
buttonTop.className = "myElement";
buttonTop.className += " myButton myStyle";
buttonTop.classList.add("myElement");
buttonTop.classList.add("myButton", "myStyle");
buttonTop.setAttribute("class", "myElement");
buttonTop.setAttribute("class", buttonTop.getAttribute("class") + " myButton myStyle");
buttonTop.classList.remove("myElement", "myButton", "myStyle");
var el = document.getElementsByClassName('myclass')
el[0].classList.add('newclass');
el[0].classList.remove('newclass');
To find whether the class exists or not, use:
el[0].classList.contains('newclass'); // this will return true or false
Browser support IE8+
You can add and remove multiple classes in same way with different in-built methods:
const myElem = document.getElementById('element-id');
//add multiple classes
myElem.classList.add('class-one', 'class-two', 'class-three');
//remove multiple classes
myElem.classList.remove('class-one', 'class-two', 'class-three');
2 great ways to ADD:
But the first way is more cleaner, since for the second you have to add a space at the beginning. This is to avoid the class name from joining with the previous class.
element.classList.add("d-flex", "align-items-center");
element.className += " d-flex align-items-center";
Then to REMOVE use the cleaner way, by use of classList
element.classList.remove("d-grid", "bg-danger");
guaranteed to work on new browsers. the old className way may not, since it's deprecated.
<element class="oneclass" />
element.setAttribute('class', element.getAttribute('class') + ' another');
alert(element.getAttribute('class')); // oneclass another
Since I could not find this answer nowhere:
ES6 way (Modern Browsers)
el.classList.add("foo", "bar", "baz");
just use this
element.getAttributeNode("class").value += " antherClass";
take care about Space to avoid mix old class with new class
Perhaps:
document.getElementById("myEle").className = "class1 class2";
Not tested, but should work.
Try this:
function addClass(element, value) {
if(!element.className) {
element.className = value;
} else {
newClassName = element.className;
newClassName+= " ";
newClassName+= value;
element.className = newClassName;
}
}
Similar logic could be used to make a removeClass function.
In modern browsers, the classList API is supported.
This allows for a (vanilla) JavaScript function like this:
var addClasses;
addClasses = function (selector, classArray) {
'use strict';
var className, element, elements, i, j, lengthI, lengthJ;
elements = document.querySelectorAll(selector);
// Loop through the elements
for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
element = elements[i];
// Loop through the array of classes to add one class at a time
for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
className = classArray[j];
element.classList.add(className);
}
}
};
Modern browsers (not IE) support passing multiple arguments to the classList::add
function, which would remove the need for the nested loop, simplifying the function a bit:
var addClasses;
addClasses = function (selector, classArray) {
'use strict';
var classList, className, element, elements, i, j, lengthI, lengthJ;
elements = document.querySelectorAll(selector);
// Loop through the elements
for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
element = elements[i];
classList = element.classList;
// Pass the array of classes as multiple arguments to classList::add
classList.add.apply(classList, classArray);
}
};
Usage
addClasses('.button', ['large', 'primary']);
Functional version
var addClassesToElement, addClassesToSelection;
addClassesToElement = function (element, classArray) {
'use strict';
classArray.forEach(function (className) {
element.classList.add(className);
});
};
addClassesToSelection = function (selector, classArray) {
'use strict';
// Use Array::forEach on NodeList to iterate over results.
// Okay, since we’re not trying to modify the NodeList.
Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
addClassesToElement(element, classArray)
});
};
// Usage
addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])
The classList::add
function will prevent multiple instances of the same CSS class as opposed to some of the previous answers.
Resources on the classList API:
- Can I use
- MDN
- David Walsh
- HTML5 Doctor
the Element.className += " MyClass";
is not recommended approach because it will always add these classes whether they were exit or not.
in my case, I was uploading an image file and adding classes to it, now with this each time you upload an image it will add these class whether they exist or not,
the recommended way is Element.classList.add("class1" , "class2" , "class3");
this way will not add extra classes if they already there.
Maybe this will help you learn:
//<![CDATA[
/* external.js */
var doc, bod, htm, C, E, addClassName, removeClassName; // for use onload elsewhere
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
addClassName = function(element, className){
var rx = new RegExp('^(.+\s)*'+className+'(\s.+)*$');
if(!element.className.match(rx)){
element.className += ' '+className;
}
return element.className;
}
removeClassName = function(element, className){
element.className = element.className.replace(new RegExp('\s?'+className), '');
return element.className;
}
var out = E('output'), mn = doc.getElementsByClassName('main')[0];
out.innerHTML = addClassName(mn, 'wow');
out.innerHTML = addClassName(mn, 'cool');
out.innerHTML = addClassName(mn, 'it works');
out.innerHTML = removeClassName(mn, 'wow');
out.innerHTML = removeClassName(mn, 'main');
}); // close load
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div id='output'></div>
</div>
</body>
</html>
addClass(element, className1, className2){
element.classList.add(className1, className2);
}
removeClass(element, className1, className2) {
element.classList.remove(className1, className2);
}
removeClass(myElement, 'myClass1', 'myClass2');
addClass(myElement, 'myClass1', 'myClass2');
ClassList add
var dynamic=document.getElementById("dynamic");
dynamic.classList.add("red");
dynamic.classList.add("size");
dynamic.classList.add("bold");
.red{
color:red;
}
.size{
font-size:40px;
}
.bold{
font-weight:800;
}
<div id="dynamic">dynamic css</div>
精彩评论