Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove p element from DOM tree with javascript

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>
like image 391
AKnox Avatar asked May 19 '11 09:05

AKnox


People also ask

How do you remove an element from a DOM tree?

To remove an element from the DOM, you follow these steps: First, select the target element that you want to remove using DOM methods such as querySelector() . Then, select the parent element of the target element and use the removeChild() method.

How do you remove child element from DOM?

Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove(). Another method to remove all child of a node is to set it's innerHTML=”” property, it is an empty string which produces the same output.

How do I remove text from a DOM?

Remove a Text Node Set the variable x to be the first title element node. Set the variable y to be the text node to remove. Remove the element node by using the removeChild() method from the parent node.

How do you remove an element in JavaScript?

In JavaScript, an element can only be deleted from its parent. To delete one, you have to get the element, find its parent, and delete it using the removeChild method.


2 Answers

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);
        }
    }
}
like image 55
wong2 Avatar answered Sep 22 '22 00:09

wong2


  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.
like image 42
Quentin Avatar answered Sep 22 '22 00:09

Quentin