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);
Reference:
JavaScript Document createElement reference
Share "How to create HTML element with attributes in JavaScript?"
Related snippets:
- Create HTML element with attributes in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get elements by data attribute in JavaScript
- Add class to the clicked element in JavaScript
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add data attribute to element in JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Toggle fullscreen and normal mode with JavaScript
- Play video in fullscreen with vanilla JavaScript
- Select HTML elements by CSS selectors in vanilla JavaScript
- Exit from fullscreen mode on click in JavaScript
- Switch browser to fullscreen mode with JavaScript
- Get the value of text input field in JavaScript
- Get element with data- attribute using vanilla JavaScript
- Get the value of selected radio button in JavaScript
- Get selected option from select using JavaScript
- Check if element is hidden in JavaScript
Tags:
create, add, html, element, attribute, class, id, javascript Technical term:
Create HTML element with attributes in JavaScript