Borislav Hadzhiev
Fri Jan 07 2022·2 min read
Photo by Tim Marshall
To create an element and set its text content:
document.createElement()
method to create the element.textContent
property to set the element's text content.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'); // ✅ Add text content to element el.textContent = 'Hello world'; // ✅ Or set the innerHTML of the element // el.innerHTML = `<span>Hello world</span>`; // ✅ (Optionally) Set Attributes on Element el.setAttribute('title', 'my-title'); // ✅ (Optionally) Set styles on Element // el.style.backgroundColor = 'salmon'; // el.style.color = 'white'; // ✅ 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.
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.
Here is an example that sets the inner HTML of the element.
const el = document.createElement('div'); el.innerHTML = ` <span style="background-color: salmon; color: white;"> Hello world </span> `; // ✅ (Optionally) Set Attributes on Element el.setAttribute('title', 'my-title'); // ✅ (Optionally) Set styles on Element // el.style.backgroundColor = 'salmon'; // el.style.color = 'white'; // ✅ add element to DOM const box = document.getElementById('box'); box.appendChild(el);
I used backticks `` (not single quotes) to wrap the HTML string because backticks allow us to easily create a multi-line string.
innerHTML
property with user provided data without escaping it. This would leave your application open to cross-site scripting attacks.If you need to set attributes on the element, use the setAttribute method.
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.In the example, we set the value of the element's title
attribute to
my-title
.
const el = document.createElement('div'); el.innerHTML = ` <span style="background-color: salmon; color: white;"> Hello world </span> `; el.setAttribute('title', 'my-title');
You can set styles on the element by setting properties on its style
object.
const el = document.createElement('div'); el.innerHTML = ` <span> Hello world </span> `; el.style.backgroundColor = 'salmon'; el.style.color = 'white';
Note that multi-word properties are camel-cased when using the style
object.