I have an element that already has a class:
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 replace all existing classes with one or more new classes, set the className attribute:
document.getElementById("MyElement").className = "MyClass";
(You can use a space-delimited list to apply multiple classes.)
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.
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');
For those using Lodash and wanting to update className
string:
// 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()
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:
<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.
Use element.classList.add to add a class:
element.classList.add("my-class");
And element.classList.remove to remove a class:
element.classList.remove("my-class");
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.
<div id="div1" class="someclass">
<img ... id="image1" name="image1" />
</div>
Then
var d = document.getElementById("div1");
d.className += " otherclass";
Note the space before otherclass
. It's important to include the space otherwise it compromises existing classes that come before it in the class list.
See also element.className on MDN.
first, give the div an id. Then, call function 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>