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
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.";
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.
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.
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 ().
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With