Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JScript Check if element exists and remove it

I'm trying to write a simple function in javascript to check if an element exists in the DOM and if it does remove, and if it doesn't, append it to the page, so far i've got this

        if document.contains(document.getElementById("submitbutton") {
            document.getElementById("submitbutton").remove();
}   else {
        lastDiv.appendChild(submitButton);  
        }

(lastDiv is just the div I want to append the div 'submitButton' to) Yet i'm getting the error "Uncaught ReferenceError: myFunction is not defined"

Any help? I'm aware this is a very newbie question, sorry about that

like image 987
howdybaby Avatar asked Feb 05 '14 23:02

howdybaby


People also ask

How to check if an element exists using JavaScript?

Approach 1: First, we will use document.getElementById () to get the ID and store the ID into a variable. Then compare the element (variable that store ID) with ‘null’ and identify whether the element exists or not. ID exists using JavaScript? + "element exists using JavaScript.";

How to check the existence of an element in the Dom?

This article will explain how we can check the existence of an element in the DOM with different methods. We can use the function getElementById to verify if an element exists in DOM using the element’s Id. In the following example we will verify that the element <a id="Anchor Id" href="#">Click Here</a> exists in DOM.

What is getElementsByClassName () in JavaScript?

The Function getElementsByClassName () is used to find the element in the DOM using its class name. An example to the class name value is ClassExample in element <a class="ClassExample"></a>. It will return one or more elements if any element is found or null if the element does not exist.

How to find the element using its ID in JavaScript?

Similar to that we use the getElementById () function to find the element using its Id, we also have many other functions that perform the same operation by with deffrernt criteria like getElementsByClassName (), getElementsByName () and getElementsByTagName ().


1 Answers

There is a syntax error in the code, if statements require parens

if (document.contains(document.getElementById("submitbutton"))) {
            document.getElementById("submitbutton").remove();
}   else {
        lastDiv.appendChild(submitButton);  
}
like image 167
Kevin Bowersox Avatar answered Oct 18 '22 01:10

Kevin Bowersox