Keroro Chan
Keroro Chan

Reputation: 99

html how to check whether the element with id exist or not?

I press a button to insert a div with let's say id="exist" using javascript. Initially, there are no such elements. How can I check check whether the element with id exist or not? I have used the following code:

if(document.getElementById("tag_exist").innerHTML == "null")
        console.log("1111");

But it does not print out 1111 in the console but the error(Uncaught TypeError: Cannot read property 'innerHTML' of null). The problem is that it does not execute the code left which I need to run. How can I check check whether the element with id exist or not?

Upvotes: 0

Views: 4385

Answers (6)

Faktor 10
Faktor 10

Reputation: 1878

By calling innerHTML property on the element the assumption you are making, or more specifically that the javascript engine in the browser is making is that the tag already exists. But it doesnt so instead you get as expected the error. Cannot read property 'innerHTML' of null. As suggested by @Quentin the correct way is to actually see if the element you are asking for exists. The if check is a truthy/falsy check which simply says if the element object exists it will return true, if not (i.e. it is undefined) it will return false. See my code sample maybe makes it a bit clearer. (easier to test on JSBIN)

<!DOCTYPE html>
<html>
<head>
   <title>Demonstrate ID exists tag checking</title>
</head>
<body>

  <!-- tag doesnt exist yet. Click button it creates a div.
  second time you click the button console message displayed. -->


  <button onclick="addDiv()">Add a div with id='tag exist'</button>

  <script>

  function addDiv() {

    if(document.getElementById("tag_exist")) {
      // do nothing div already exists  
      console.log("Div with id='tag_exists' already");
    } else {
     // append the div to body
     var div = document.createElement("div");
      div.setAttribute("id", "tag_exist")
      div.innerHTML = "I now exist";
      document.body.appendChild(div);
    }
 }

  </script>

</body>
</html>

Upvotes: 1

morels
morels

Reputation: 2105

The issue in your code is that if there is no id=tag_exits element, the browser engine throws 'Cannot read innerHTML property from undefined', or nothing happens. This happens because getElementById returns undefined if no element is found.

You can choose to write:

if((document.getElementById("tag_exist") || {}).innerHTML == null)
  // code

or

if((document.getElementById("tag_exist"))
  // code

The last choice stands for:

if((document.getElementById("tag_exist") !== undefined && (document.getElementById("tag_exist") !== null))
  // code

Upvotes: 0

JanLeeYu
JanLeeYu

Reputation: 1001

try this

if(document.getElementById("exist") != undefined) {
      //exists
}

Upvotes: 0

Pandiyan Cool
Pandiyan Cool

Reputation: 6565

if loop will execute the block if id isn't present

if (!document.getElementById("tag_exist")) {
// didn't exist
}

Upvotes: 3

Quentin
Quentin

Reputation: 943569

Test if the element exists. Don't fetch the element and then try to read the innerHTML of whatever you got back (since that will throw an exception if the element doesn't exist)

if (document.getElementById("tag_exist"))

Upvotes: 7

Asons
Asons

Reputation: 87191

You should do like this before you access any properties or methods.

if(document.getElementById("tag_exist")) {
  //exists
}

Upvotes: 2

Related Questions