Add another class to a div
If the element has no class, give it one. Otherwise, append a space followed by the new className:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
Use Element.classList
document.getElementById('hello').classList.add('someClass');
The .add
method will only add the class if it doesn't already exist on the element. So no need to worry about duplicate class names.
Well you just need to use document.getElementById('hello').setAttribute('class', 'someclass');
.
Also innerHTML
can lead to unexpected results! Consider the following;
var myParag = document.createElement('p');
if(under certain age)
{
myParag.text="Good Bye";
createCookie('age', 'not13', 0);
return false;
{
else
{
myParag.text="Hello";
return true;
}
document.getElementById('hello').appendChild(myParag);
You can append a class to the className
member, with a leading space.
document.getElementById('hello').className += ' new-class';
See https://developer.mozilla.org/En/DOM/Element.className