- Instant help with your JavaScript coding problems

Create HTML element with attributes in JavaScript

Question:
How to create HTML element with attributes in JavaScript?
Answer:
const div = document.createElement('div');
div.setAttribute('class', 'flex justify-center');
div.setAttribute('id', 'test-div');
Description:

To create an HTML element with various attributes like class or id you need to use the document.createElement() method and then the setAttribute method on the created element. If the element is ready you can add it to the page using the appendChild() or prepend() methods.

const div = document.createElement('div');
div.setAttribute('class', 'flex justify-center');
div.setAttribute('id', 'test-div');
div.innerHTML = `This is my div`;

document.body.appendChild(div);

 

Share "How to create HTML element with attributes in JavaScript?"