JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to set the value of an attribute in JavaScript?

If you want to set the attribute value of an HTML element, then use the setAttribute() method. The format for the setAttribute() method is

htmlElement.setAttribute(attributeName, attributeValue)

For example, to set the src attribute of the img element, run the following code.

HTML Code

<img id="logo" />

JavaScript Code

let image = document.getElementById('logo');
image.setAttribute('src', "https://www.tutorialsandyou.com/images/javascript.png");

The interesting thing about the setAttribute() method is that you can also set the value data-* attribute.

For example, to set the value of the data-color attribute of an img element, you have to select the img element and then call the setAttribute() method.

<img src="/images/javascript.png" id="logo" />
let image = document.getElementById('logo');
image.setAttribute('data-color', "yellow");

Recommended Posts