Check if div exists with javascript

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?

+72
javascript html if-statement
Jun 04 '12 at 18:22
source share
7 answers
 var myElem = document.getElementById('myElementId'); if (myElem === null) alert('does not exist!'); 
+122
Jun 04 '12 at 18:27
source share
 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 )

+68
Jun 04 '12 at 18:27
source share

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 
+9
Jun 04 '12 at 18:25
source share

Check out both JavaScript and jQuery codes:

JavaScript:

 if (!document.getElementById('MyElementId')){ alert('Does not exist!'); } 

JQuery

 if (!$("#MyElementId").length){ alert('Does not exist!'); } 
+5
Apr 29 '15 at 10:36
source share

getElementById returns null if there is no such element.

+3
Jun 04 '12 at 18:24
source share

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'); } 
+1
Aug 29 '13 at 14:08
source share

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.

+1
Feb 06 '17 at 23:01
source share



All Articles