JScript Check if element exists and remove it
Asked Answered
F

2

16

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

Furthest answered 5/2, 2014 at 23:56 Comment(4)
We need more code than this. Where is myFunction?Entomophagous
its a very long function, but this is the only part of it that is causing an error, i've debugged the restFurthest
@Furthest No you haven't, there is a problem with myFunctionLaetitia
but when i remove these lines of code from the function, the rest of it runs fine, yet when I add these lines in, the whole thing breaksFurthest
E
35

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);  
}
Entomophagous answered 6/2, 2014 at 0:7 Comment(1)
if (document.contains(document.getElementById("submitbutton")) should change to if (document.contains(document.getElementById("submitbutton"))) You forgot one paramLyte
R
3

Check if element exists:

function removeID(_id ){ 
    var e=document.getElementById(_id);
    if(e!==null) e.remove();
}
removeID( "myElement" );
Rifle answered 16/9, 2022 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.