6

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)

Black
  • 18,150
  • 39
  • 158
  • 271

2 Answers2

16

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");
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
3
   var x = document.getElementsByClassName("contactForm")[0];
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30