Checking for div existence is quite simple
if(document.getif(document.getElementById('if')){ }
But how can I check if a div with the given id exists?
var myElem = document.getElementById('myElementId'); if (myElem === null) alert('does not exist!');
if (!document.getElementById("given-id")) { //It does not exist }
The document.getElementById("given-id") operator returns null if the element with given-id does not exist and null is false, which means that it is false when evaluated in an if-statement. ( other fake values )
document.getElementById("given-id")
null
given-id
Try to get the element with id and check if the return value is null:
document.getElementById('some_nonexistent_id') === null
If you use jQuery you can do:
$('#some_nonexistent_id').length === 0
Check out both JavaScript and jQuery codes:
JavaScript:
if (!document.getElementById('MyElementId')){ alert('Does not exist!'); }
JQuery
if (!$("#MyElementId").length){ alert('Does not exist!'); }
getElementById returns null if there is no such element.
getElementById
This works with:
var element = document.getElementById('myElem'); if (typeof (element) != undefined && typeof (element) != null && typeof (element) != 'undefined') { console.log('element exists'); } else{ console.log('element NOT exists'); }
There is an even better solution. You do not even need to check if the element returns null . You can simply do this:
if (document.getElementById('elementId')) { console.log('exists') }
This code will only write exists to the console if the item really exists in the DOM.
exists