close

How to find if element with specific id exists or not

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to find if element with specific id exists or not in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to find if element with specific id exists or not ?

  1. How to find if element with specific id exists or not ?

    to find if element with specific id exists or not Use typeof for elements checks.
    if(typeof(element) === 'undefined') { // then field does not exist }

  2. How to find if element with specific id exists or not ?

    to find if element with specific id exists or not Use typeof for elements checks.
    if(typeof(element) === 'undefined') { // then field does not exist }

Method 1

var myEle = document.getElementById("myElement");
    if(myEle){
        var myEleValue= myEle.value;
    }

the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value

Method 2

Use typeof for elements checks.

if(typeof(element) === 'undefined')
{
// then field does not exist
}

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment