[英]How to remove class attribute from div?
I am using JavaScript and I want to add/remove a Class attribute if a button is clicked. 我正在使用JavaScript,如果单击一个按钮,我想添加/删除Class属性。 I am able to add the class, but I don't know how to remove it.
我可以添加该类,但我不知道如何删除它。 how can I do that?
我怎样才能做到这一点?
window.onload = function(){
var buttonGo = document.getElementsByTagName('button')[0];
var buttonCom = document.getElementsByTagName('button')[1];
var box = document.getElementById('box');
buttonGo.onclick = function(){
box.setAttribute('class','move');
}
buttonCom.onclick = function(){
// how to remove class name?
}
}
box.removeAttribute("class")
应该可以工作。
function hasClass(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
You can use RegExp in theses three functions to check class existance, add class, and remove class. 您可以在这三个函数中使用RegExp来检查类存在,添加类和删除类。 Here is the source openjs
这是源openjs
Simple: 简单:
box.removeAttribute('class');
See https://developer.mozilla.org/en/DOM/element.removeAttribute 请参阅https://developer.mozilla.org/en/DOM/element.removeAttribute
In the future-ish, you can also consider Element.classList . 在未来,你也可以考虑Element.classList 。
var d = document.getElementsByTagName('div')[0];
d.classList; // []
d.classList.add('foo'); // undefined
d.classList; // ["foo"]
d.classList.remove('foo'); // undefined
d.classList; // []
I say future-ish b/c you have to consider this IE < 10. 我说未来是b / c你必须考虑这个IE <10。
Try this : 试试这个 :
window.onload = function(){
var buttonGo = document.getElementsByTagName('button')[0];
var buttonCom = document.getElementsByTagName('button')[1];
var box = document.getElementById('box');
buttonGo.onclick = function(){
box.setAttribute('class','move');
}
buttonCom.onclick = function(){
box.className=''
}
}
or double quotes box.className=""
或双引号
box.className=""
For cross-browser support: 对于跨浏览器支持:
buttonCom.onclick = function() {
box.className = ''; // IE
box.removeAttribute('class'); // Others
};
您应该考虑使用jQuery,而不是使用它: $('.itemclass').removeClass('classname');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.