remove p element from DOM tree with javascript
Asked Answered
B

2

6

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>
Bojorquez answered 19/5, 2011 at 9:22 Comment(0)
L
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);
        }
    }
}
Lassiter answered 19/5, 2011 at 9:26 Comment(0)
K
1
  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.
Kwang answered 19/5, 2011 at 9:31 Comment(2)
Is getElementsByClassName () an official Method in DOM Spec level 2 and 3?Garnett
I don't think so. It does appear in the HTML 5 draft though.Kwang

© 2022 - 2024 — McMap. All rights reserved.