0

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>
3
  • any client javascript library? Add it to your tags. Commented Dec 1, 2010 at 8:43
  • No. Just javascript wihtou any library. Commented Dec 1, 2010 at 8:44
  • Ok, I can use jquery but it must be inline javascript (inside html onclick attribute). There are reasons for that. Is that possible with jquery? Commented Dec 1, 2010 at 8:50

3 Answers 3

1

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);
}
"
Sign up to request clarification or add additional context in comments.

1 Comment

There's no catch. The problem you've described can easily be avoided using a regular expression in the replace() call.
1

Assuming jQuery...

HTML:

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

JS:

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

4 Comments

:( But look how easy that is!
Ok. Even if I use jquery, it must be inline javascript (inside html onclick attribute). There are reasons for that. Is that possible with jquery?
It is. onclick="$('.some_class').removeClass('some_class')"
@Richard Knop: Any amount of javascript code can be written inline! Even complex multi-line scripts can be. The whole minified jQuery library is written in a single line for what it's worth. The only thing you have to be careful about are strings to not mix them with outside ones.
1

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)
        }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.