Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from DOM with vanilla javascript [duplicate]

I have a form and try to delete it on button click.

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
    <button onclick="remove()">remove</button>

    <form action="test.html" class="contactForm" dir="ltr" enctype="multipart/form-data" method="post">
        <ol>
            <li class="csc-form-9 csc-form-element csc-form-element-textline">
                <label for="field-9">Vorname</label>
                <input class="inputFormText" id="field-9" name="tx_form[firstname]" type="text"/>
            </li>
            <li class="csc-form-10 csc-form-element csc-form-element-textline">
                <label for="field-10">Nachname</label>
                <input class="inputFormText" id="field-10" name="tx_form[lastname]" type="text"/>
            </li>

        </ol>
    </form>

    <script>
    function remove()
    {
        var x = document.getElementsByClassName("contactForm");

        console.log(x);

        x.remove();
    }
    </script>

</body>
</html>

According to this article it should be possible by just calling remove() on the DOM element. However, I get:

(index):30 Uncaught TypeError: x.remove is not a function at remove ((index):30) at HTMLButtonElement.onclick ((index):7)

like image 874
Black Avatar asked Jan 23 '17 14:01

Black


People also ask

How do I completely remove an element from a DOM?

HTML DOM Element remove() The remove() method removes an element (or node) from the document.

How do you clone a DOM element?

Use the node. cloneNode() method to clone the node. Pass true into the cloneNode() method to create a deep clone of a DOM element.

How do I clone a div using JavaScript?

You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.

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

The getElementsByClassName method returns an array-like collection of elements, so get the element by index.

x[0].remove();

Or use querySelector method to get a single element.

var x = document.querySelector(".contactForm");
like image 121
Pranav C Balan Avatar answered Oct 09 '22 20:10

Pranav C Balan


   var x = document.getElementsByClassName("contactForm")[0];
like image 37
Vladu Ionut Avatar answered Oct 09 '22 21:10

Vladu Ionut