Today, you will learn how to access dynamically created elements in JavaScript.

Suppose, you create an <div> element using JavaScript createElement() method. Now, you want to access the <div> element.

Access created div elements in JavaScript #

Before we start the details, let's look at the example below.

  const div = document.createElement("DIV");
  div.innerHTML = "I am a new div element.";
  div.id = "my-div";
  document.body.appendChild(div);

  const newDiv = document.getElementById("my-div");
  1. In the above example, first we have created an div element using the createElement() method.
  2. Then, we have set its value using the innerHTML property and also give an id to the div element (so that, we can access it later).
  3. Now add the created div element to the body element using the appendChild() method.
  4. Finally, we can access the above div element using getElementById() method.