admin管理员组

文章数量:1297126

I would like to be able to determine if a parent node, whose ID I know, has direct child nodes, and if such nodes are detected, remove them. The nodes, if they exist, will always follow some text, so I don't think I can use firstChild or lastChild.

Ideally, I would use Javascript to minimize the performance hit. Although JQuery would also work if necessary.

The code is like this:

<a id="anchorID">some text 
<span class="spanClass">some span text</span>
</a>

Any help, as always, is appreciated.

I would like to be able to determine if a parent node, whose ID I know, has direct child nodes, and if such nodes are detected, remove them. The nodes, if they exist, will always follow some text, so I don't think I can use firstChild or lastChild.

Ideally, I would use Javascript to minimize the performance hit. Although JQuery would also work if necessary.

The code is like this:

<a id="anchorID">some text 
<span class="spanClass">some span text</span>
</a>

Any help, as always, is appreciated.

Share Improve this question asked Feb 1, 2012 at 22:39 robert smithrobert smith 9812 gold badges11 silver badges20 bronze badges 1
  • 2 Using jQuery is a negligable performance hit, and will save you code and x-browser headaches. – calebds Commented Feb 1, 2012 at 22:50
Add a ment  | 

5 Answers 5

Reset to default 4

If you'd like to remove the child nodes in your anchor, and you're ok with jQuery, then it's quite simply:

$("#anchorId").empty();

EDIT

You want to remove the span only?

$("#anchorID span").remove();

That will remove all spans in the anchor. If you wanted to remove only the first span, then you could do

$("#anchorID span:first").remove();

With jQuery and the HTML provided, it's as simple as $("#anchorId").remove(".spanClass");

plain ol js

var target = document.getElementById("anchorId");
if(target.hasChildNodes())
{
  var children = new Array();
  children = target.childNodes();
  for(child in children)
  {
    target.removeChild[child];
  }
}

With pure JavaScript use element.removeChild: http://jsfiddle/JetxN/

If you'd like not to remove top level textNodes (i.e. "some text" anchor text):

$('#anchorID').children().remove();
  • DEMO

本文标签: javascriptHow do I remove specific child elements within an element of known IDStack Overflow