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");
- In the above example, first we have created an div element using the createElement() method.
- 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).
- Now add the created div element to the body element using the appendChild() method.
- Finally, we can access the above div element using getElementById() method.
save
listen
AI Answer
How to access dynamically created elements in JavaScript
1
Today, you will learn how to access dynamically created elements in JavaScript. Suppose,…
asked
Apu
1 answers
2915
Today, you will learn how to access dynamically created elements in JavaScript. Suppose,…
Answer Link
answered
Apu
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 »