将另一个类添加到div [英] Add another class to a div

查看:80
本文介绍了将另一个类添加到div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个检查表单提交年龄的函数,然后根据其年龄在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 don't 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';
  }

这篇关于将另一个类添加到div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆