How to check if an element exists | JavaScript

/ #JavaScript


You often want to check the value of an element or manipulate it some how. But if you do this without knowing if it exists or not, you might get an error.

So how do you make sure that this doesn't happen to you?

You can check if the element exists by checking the type and if it's null first.

var element =  document.getElementById('the-elements-id');
if (typeof(element) != 'undefined' && element != null) {
    console.log('The element exists!');
}

This code will look for an element called "the-elements-id". And then it checks if that element is not undefined and is not null. This way, you can be sure that it's safe to execute code on the element variable.


Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.