使用javascript将另一个类添加到div [英] Add another class to a div with javascript
问题描述
我有一个函数可以检查表单提交的年龄,然后根据年龄在div中返回新内容。现在我只是使用getElementById来替换html内容。我认为如果我也可以为div添加一个类,那对我来说会更好。所以例如我有..
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;
}
我想做的是将所有东西放在div中并且如果返回false那个div消失了,并被其他内容所取代..我可以通过纯javascript实现这个目标的任何想法。我不想在这个特定的函数中使用jQuery。
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.
推荐答案
如果元素没有类,请给它一个。否则,追加一个空格,后跟新的className:
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';
}
这篇关于使用javascript将另一个类添加到div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!