Richard Knop
Richard Knop

Reputation: 83697

How to remove a class from a page inside onclick html attribute?

So how can I remove a class from all HTML elements on the page?

I need to to it inside the onclick html element. So:

<div onclick="remove class 'someClass' from all elements on the page"></div>

Upvotes: 0

Views: 2959

Answers (3)

Sedat Kapanoglu
Sedat Kapanoglu

Reputation: 47640

Here is a raw JavaScript solution (removes some_class class from all elements in document):

onclick="
for (var i = 0, elements = document.getElementsByTagName('*'); i < elements.length; i++) {
  var attr = elements[i].getAttribute('class'),
      newAttr = attr.replace(/\bsome_class\b/i, '');
  if(newAttr != attr) elements[i].setAttribute('class', attr);
}
"

Upvotes: 1

Daniel
Daniel

Reputation: 2381

to remove a class from an element

 element.className = element.className.replace(/className/g,'');

you will have to write a recursive function to go over all the element in a page using the childNodes property

 ReomoveClass(element, ClassName)
 {
        element.className = element.className.replace(new RegExp(ClassName,'g'),'');
        for(var i=0; i<element.childNodes;i++)
        {
             ReomoveClass(element.childNodes[i], ClassName)
        }
 }

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187004

Assuming jQuery...

HTML:

<div id="my_button">Click me</div>

JS:

$('#my_button').click(function() {
  $('.some_class').removeClass('some_class');
});

Upvotes: 1

Related Questions