开发者

Process HTML in javascript

I would like to remove all ins开发者_如何学Pythontances 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?


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.


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.


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


Using jQuery you could do:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜