Borislav Hadzhiev
Fri Jan 07 2022·2 min read
Photo by Dương Trần Quốc
To create an element with attributes:
document.createElement()
method to create the element.setAttribute()
method to add one or more attributes to the element.appendChild()
method.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"></div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
// ✅ Create element const el = document.createElement('div'); // ✅ Set Attributes on Element el.setAttribute('id', 'my-id'); el.setAttribute('title', 'my-title'); el.setAttribute('disabled', ''); // ✅ Set styles on Element el.style.backgroundColor = 'salmon'; el.style.color = 'white'; el.style.width = '150px'; el.style.height = '150px'; // ✅ Add text content to element el.textContent = 'Hello world'; // ✅ Or set the innerHTML of the element // el.innerHTML = `<span>Hello world</span>`; // ✅ add element to DOM const box = document.getElementById('box'); box.appendChild(el);
We used the document.createElement method to create the element.
div
in the example).The createElement
method returns the newly created element.
We used the setAttribute method to set multiple attributes on the element.
The setAttribute
method takes 2 parameters:
name
- the name of the attribute whose value is to be set.value
- the value to assign to the attribute.Note that it's a best practice to set boolean attributes, such as disabled
, to
an empty string. As long as boolean attributes are set to any value, they take
effect.
If you need to add styles to the element, use the style
object instead.
Notice that multi-word style names are camel-cased when accessed on the style
object.
You can use the textContent property to set the element's text content or the innerHTML property to set the element's inner HTML markup.
innerHTML
property with user provided data without escaping it. This would leave your application open to cross-site scripting attacks.You can use the appendChild method to add the element to the page.
The method adds a node to the end of the list of children of the element it was called on.
If I load the page from the example above, I can see that the attributes are applied on the element.