views:

64

answers:

4

I would like to remove all instances of a .class in an html.

remove class "s"

 remove <span class="s">some text</span> in html

Output

 remove some text in html

What's the easiest way to do this?

A: 

Using jQuery you could do:

$(".s").remove();

http://api.jquery.com/remove/

JochenJung
Will this leave the inner html of the element?
Brendan Bullen
No, it will not. It just removes the whole thing.
Pointy
No, it does not. But I understand the question as this is what it should do. The inner HTML belongs to the instance of the class s.If this is not the behaviour wanted, please let me know and I will edit.
JochenJung
How can I make it just remove the html tag? in this case the span tag and leave the text
Comma
Then see Gerd G's solution.
JochenJung
A: 

replaceNode?

http://www.webreference.com/js/column43/replace.html

mplungjan
+2  A: 

Assuming you want to remove it from just this class. Here's how to keep just the text:

$(".s").each(function(){
  $(this).replaceWith($(this).text());
});

Code in action.

And if you want to keep the HTML:

$(".s").each(function(){
  $(this).replaceWith($(this).html());
});

And here's that code in action.

Gert G
+1  A: 

Here's a plain JavaScript solution. It might look a bit long at first sight, but it simply does what you want:

function moveElements(root) {
  var parent = root.parentNode,
      e = root.firstChild;
  while (e != null) {
    var next = e.nextSibling;
    parent.insertBefore(e, root);
    e = next;
  }
  parent.removeChild(root);
}

function removeClass(root, name) {
  var e = root.firstChild;
  while (e != null) {
    var next = e.nextSibling;
    if (e.nodeType == 1) { // element node
      if (e.className == name)
        moveElements(e);   // move children outside this element
      else
        removeClass(e, name);  // else recursively scan this element
    }
    e = next;
  }
}

removeClass recursively scans elements looking for the specified class, and if found, calls moveElements, which moves the children outside and removes the original element. To run it through the entire document, removing the class s (from your example), call it like this:

removeClass(document.documentElement, 's');

Here's a working example on JSBin.

casablanca