How can assign multiple css classes to an html element through javascript without using any libraries?
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');
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>
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");
Since I could not find this answer nowhere:
ES6 way (Modern Browsers)
el.classList.add("foo", "bar", "baz");
Try doing this...
document.getElementById("MyElement").className += " MyClass";
Got this here...