JavaScript element.setAttribute() Method

You are Here:

JavaScript element.setAttribute() Method

The element.setAttribute() method sets the value of an attribute on the specified element.

Note: If the specified attribute is already present, the value in it will be updated.

Tips: To get the current value of an attribute, use element.getAttribute().

Tips: To remove an attribute, call element.removeAttribute().

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <a>Learn jQuery</a> <p>Click on the button to set 'href' for the above anchor tag.</p> <button onclick="myFunction()">Click Me</button> <script> var elem = document.getElementsByTagName("a")[0]; function myFunction(){ elem.setAttribute("href", "/jquery") } </script> </body> </html>

Syntax

element.setAttribute(attrName, value)

Parameter Values

ValueTypeExplanation
attrNameRequiredA DOMString specifying the name of the attribute whose value is to be set.
valueRequiredA DOMString containing the value to assign to the attribute.

Set CSS Attribute

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Change my color</p> <p>Click on the button to set 'style' for the above paragraph.</p> <button onclick="myFunction()">Click Me</button> <script> var elem = document.getElementsByTagName("p")[0]; function myFunction(){ elem.setAttribute("style", "color:red;") } </script> </body> </html>

Example

HTML Online Editor
<!DOCTYPE html> <html> <head> <style> .one{ color: green; font-size: 20px; } </style> </head> <body> <p>Change my appearance</p> <p>Click on the button to set 'class' for the above paragraph.</p> <button onclick="myFunction()">Click Me</button> <script> var elem = document.getElementsByTagName("p")[0]; function myFunction(){ elem.setAttribute("class", "one") } </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author