Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add another class to a div

Tags:

javascript

I have a function that checks the age of a form submission and then returns new content in a div depending on their age. Right now I am just using getElementById to replace the HTML content. BUt I think would work better for me if I could also add a class to a div as well. So for example I have.

if (under certain age) {
    document.getElementById('hello').innerHTML = "<p>Good Bye</p>"; 
    createCookie('age','not13',0)
    return false;
} else {
    document.getElementById('hello').innerHTML = "<p>Hello</p>";  
    return true;
}

What I would like to do is have everything in a div and if return false then that div disappears and is replaced with other content. Can I get any ideas on a good way to achieve this with pure JavaScript. I don't want to use jQuery for this particular function.

like image 623
Zac Avatar asked Apr 29 '10 18:04

Zac


People also ask

Can you add 2 classes to a div?

Multiple ClassesHTML elements can belong to more than one class. To define multiple classes, separate the class names with a space, e.g. <div class="city main">. The element will be styled according to all the classes specified.

How can I add two CSS class in one div?

To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.

How do I add a class to an existing class?

jQuery addClass() Method The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

Can a HTML tag have 2 classes?

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.


3 Answers

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';
  }
like image 62
karim79 Avatar answered Oct 11 '22 13:10

karim79


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.

like image 60
Rich McCluskey Avatar answered Oct 11 '22 14:10

Rich McCluskey


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

like image 24
meagar Avatar answered Oct 11 '22 15:10

meagar