JavaScript > DOM Manipulation > Modifying Elements > setAttribute() and getAttribute()

Change styles with setAttribute()

Use setAttribute() in JavaScript to dynamically change HTML styles elements. This tutorial provides practical code examples and explanations to help you understand these DOM manipulation techniques.

Introduction to setAttribute() and style

setAttribute() can be used to apply styles to a given HTML element. However it's important to set attribute style with a single string like this: 'color: red; font-size: 20px;'. Because of this, for the most common use cases to apply styles, it is recommended to use element.style.property instead.

Change styles with setAttribute()

This example demonstrates how to set the style of an element by using a single string. Style must be defined in a single string using ; separator.

const element = document.getElementById('myElement');

// Setting an attribute
element.setAttribute('style', 'color: red; font-size: 20px;');

Change styles with setAttribute() with variables

This example demonstrates how to set the style of an element by using variables.

const element = document.getElementById('myElement');

const myColor = 'red';
const myFontSize = '20px';

// Setting an attribute
element.setAttribute('style', `color: ${myColor}; font-size: ${myFontSize};`);

setAttribute() vs element.style.property

Setting styles with setAttribute is not recommended and element.style.property must be used for the most common use cases.

  • setAttribute: Sets style attribute using a single string and override existing style
  • element.style.property: Allow you to change a specific style without rewrite other styles

FAQ

  • What is the difference between setAttribute and style property?

    setAttribute is generally slower and style property is recommended for most cases.