3gwebtrain
3gwebtrain

Reputation: 15299

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. 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?
    }
}

Upvotes: 16

Views: 86079

Answers (8)

user1146912
user1146912

Reputation: 19

You should consider jQuery, than you can just use this: $('.itemclass').removeClass('classname');

Upvotes: -4

ynkr
ynkr

Reputation: 28034

In the future-ish, you can also consider 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.

Upvotes: 4

Brett Zamir
Brett Zamir

Reputation: 14355

For cross-browser support:

buttonCom.onclick = function() {
    box.className = ''; // IE
    box.removeAttribute('class'); // Others
};

Upvotes: 1

BJ Safdie
BJ Safdie

Reputation: 3419

box.removeAttribute("class") should work.

Upvotes: 39

lonesomeday
lonesomeday

Reputation: 237975

The nicest way to set classes with Javascript is to use the className property:

// to add
box.className = 'move';
// to remove
box.className = '';

Upvotes: 8

KJYe.Name
KJYe.Name

Reputation: 17169

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. Here is the source openjs

Upvotes: 7

Nivas
Nivas

Reputation: 18354

Simple:

box.removeAttribute('class'); 

See https://developer.mozilla.org/en/DOM/element.removeAttribute

Upvotes: 6

ant
ant

Reputation: 22948

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=""

Upvotes: 2

Related Questions