How to Change an HTML Element Using JavaScript?

Estimated read time 1 min read

To change the attributes or properties of an HTML element using JavaScript, you can select the element and set its attributes or properties to new values. Here’s an example:

// Select the element to be changed
const myElement = document.getElementById('my-element');

// Change the element's attributes
myElement.setAttribute('class', 'new-class');
myElement.setAttribute('data-id', '123');

// Change the element's properties = 'blue';
myElement.disabled = true;

In this example, getElementById('my-element') selects the element with the ID of “my-element”. The first two setAttribute() examples set the class attribute and a custom data-id attribute to the element with the values of “new-class” and “123”, respectively. The last two examples change the backgroundColor property of the element to blue and disable the element, respectively.

Note that the specific attributes and properties you can change will depend on the type of element you are working with. For example, not all elements have a class attribute or a backgroundColor property. You can check the documentation for the specific element to see which attributes and properties are available.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply