remove p element from DOM tree with javascript - Stack Overflow

This should be a simple one, and yet I need help to solve the problem:I need to remove the element wit

This should be a simple one, and yet I need help to solve the problem: I need to remove the element with the class "goup" on it from the DOM tree with javascript (eventually with prototype, but no other library). I don't only want to hide that paragraph, but remove it entirely from the DOM tree.

My solution to use getElementsByClassName does not work.

function hidegoup() {
    var goup= document.getElementsByTagName("p")
        .getElementsByClassName("goup"); 
     goup.style.display = 'none';   
     goup.removeChild();
}

THE HTML:

<div id="poems">
    <div class="poem" id="d1">
        <p class="goup">
        <a href="#">To the top of the page</a>
        </p>
    </div>
</div>

This should be a simple one, and yet I need help to solve the problem: I need to remove the element with the class "goup" on it from the DOM tree with javascript (eventually with prototype, but no other library). I don't only want to hide that paragraph, but remove it entirely from the DOM tree.

My solution to use getElementsByClassName does not work.

function hidegoup() {
    var goup= document.getElementsByTagName("p")
        .getElementsByClassName("goup"); 
     goup.style.display = 'none';   
     goup.removeChild();
}

THE HTML:

<div id="poems">
    <div class="poem" id="d1">
        <p class="goup">
        <a href="#">To the top of the page</a>
        </p>
    </div>
</div>
Share edited May 19, 2011 at 9:34 JohnP 50k13 gold badges112 silver badges141 bronze badges asked May 19, 2011 at 9:22 AKnoxAKnox 631 gold badge2 silver badges4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

if you want to remove a node from the DOM, use:

node.parentNode.removeChild(node);

as to what you want to do:

function hidegoup() {
    var p_list = document.getElementsByTagName("p");
    for(var i=p_list.length-1; i>=0; i--){
        var p = p_list[i];
        if(p.className === "goup"){
            p.parentNode.removeChild(p);
        }
    }
}
  1. getElementsByClassName returns a NodeList, not a Node. You have to iterate over it with a for loop
  2. getElementsByClassName is not supported except in recent browsers, you should probably use a library that abstracts the differences away
  3. removeChild removes the specified child of the element upon which it is called: parent.removeChild(child);, you don't call it on the element you want to remove directly.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743681148a4489405.html

相关推荐

  • remove p element from DOM tree with javascript - Stack Overflow

    This should be a simple one, and yet I need help to solve the problem:I need to remove the element wit

    1天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信