Create an Element with Style attribute using JavaScript

avatar

Borislav Hadzhiev

Fri Jan 07 20222 min read

banner

Photo by João Ferrão

Create an Element with Style attribute using JavaScript #

To create an element with a style attribute:

  1. Use the document.createElement() method to create the element.
  2. Use the setAttribute() method to set the style attribute on the element.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the examples in this article.

index.html
<!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.

index.js
// ✅ Create element const el = document.createElement('div'); // ✅ Set Style Attributes on Element el.setAttribute( 'style', 'background-color: salmon; color: white; width: 150px; height: 150px;', ); // ✅ Alternatively, 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.

The only parameter we passed to the method is the type of element to be created (div in the example).

The createElement method returns the newly created element.

We used the setAttribute method to set the style attribute on the element.

The setAttribute method takes 2 parameters:

  1. name - the name of the attribute whose value is to be set.
  2. value - the value to assign to the attribute.
If the attribute already exists, the value is updated, otherwise a new attribute is added with the specified name and value.

You can alternatively set styles on the element using the style object.

index.js
const el = document.createElement('div'); el.style.backgroundColor = 'salmon'; el.style.color = 'white'; el.style.width = '150px'; el.style.height = '150px';

Note that when setting styles using the style property, multi-name words are camel-cased.

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.

You shouldn't use the 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 style attribute is successfully set on the element.

style attribute successfully set

Use the search field on my Home Page to filter through my more than 1,000 articles.