Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu August 17, 2023 › #Element #HowTo

How to access dynamically created elements in JavaScript

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.
save
listen
AI Answer
1 Answer
Write Your Answer
  1. To create and access dynamically created elements in JavaScript, you can follow these steps:
    1. Create the Element: Use the document.createElement() method to create a new HTML element. For example, to create a new <div> element:
    Modify the Element: You can set attributes, properties, styles, and content for the newly created element. For instance, to add text content to the newly created <div> :
    Add the Element to the DOM: Use methods like appendChild() or insertBefore() to add the newly created element to an existing element in the DOM. For example, to add the new <div>  to an element with the ID container:
    4. Access the Dynamically Created Element: You can access the dynamically created element using its reference. If you need to manipulate or modify it later, you can store the reference in a variable:
    const dynamicDiv = document.getElementById('dynamicDivId');
    dynamicDiv.style.color = 'red';

    Try it Yourself »
    Reply Delete
    Share
loading
back
View All