문제

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

도움이 되었습니까?

해결책

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);  
}

다른 팁

Check if element exists:

function removeID(_id ){ 
    var e=document.getElementById(_id);
    if(e!==null) e.remove();
}
removeID( "myElement" );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top