tags:

views:

56

answers:

4

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 dont want to use jQuery for this particular function.

A: 

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

meagar
+3  A: 

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';
  }
karim79
awesome, thanks! Can you please explain a bit more this part.. ' someClass' : 'someClass' why is it defined twice like that... what does the first part do?
zac
@zac - that's the conditional operator. If `el.className` evaluates to true, the first value (after the question mark) gets assigned, if false then the second one gets assigned. It's an if..else shortcut. Take a look here: http://www.w3schools.com/JS/js_comparisons.asp
karim79
great! thank you thank you
zac
A: 

In the DOM, the class of an element is just each class separated by a space. You would just need to implement the parsing logic to insert / remove the classes as necesary.

I wonder though... why wouldn't you want to use jQuery? It makes this kind of problem trivially easy.

Tejs
A: 

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);
Jonathan Czitkovics