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
5 Answers
Reset to default 4If 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 textNode
s (i.e. "some text" anchor text):
$('#anchorID').children().remove();
- DEMO
本文标签: javascriptHow do I remove specific child elements within an element of known IDStack Overflow
版权声明:本文标题:javascript - How do I remove specific child elements within an element of known ID? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741642711a2390010.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论