Comma
Comma

Reputation: 1607

Process HTML in javascript

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?

Upvotes: 0

Views: 853

Answers (4)

mplungjan
mplungjan

Reputation: 177950

replaceNode?

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

The replaceNode method is much more intuitive than the removeNode method. While the removeNode method just removes the specified element and makes its descendents children of their grandfather, the replaceNode method deletes the whole subtree that is rooted at the specified element, and substitutes it with a new element.

var msg = "";
function printChildren()  {
   childCount = bodyNode.childNodes.length;
   msg += "childCount = " + childCount;
   for(var i = 0; i < childCount; i++)  {
     msg += "\nchildNodes["+i+"].nodeName = " + bodyNode.childNodes[i].nodeName;
   }
}
printChildren();
msg += "\nReplacing Paragraph 3\n";
var b = document.createTextNode("New Body Page");
var replacedNode = p3Node.replaceNode(b);
msg += "\nreplacedNode.nodeName = " + replacedNode.nodeName;
msg += "\nreplacedNode.childNodes.length = " + replacedNode.childNodes.length;
msg += "\np2Node.nodeName = " + p2Node.nodeName;
printChildren();
alert(msg);

Upvotes: 1

casablanca
casablanca

Reputation: 70701

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.

Upvotes: 1

Gert Grenander
Gert Grenander

Reputation: 17084

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.

Upvotes: 2

JochenJung
JochenJung

Reputation: 7213

Using jQuery you could do:

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

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

Upvotes: 0

Related Questions