Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X
Table of contents
Return Value
Example 1: Changing the Style of an Element
Example 2: Adding an Alt Text to an Image
Example 3: Setting Custom Data Attributes
Supported Browsers
Frequently Asked Questions
Can setAttribute add multiple attributes at once?
Does setAttribute work with custom data attributes?
What happens if the specified attribute already exists?
Last Updated: Mar 27, 2024

Setattribute Javascript

Author Rinki Deka
0 upvote
Roadmap to SDE career at Amazon
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM


Understanding JavaScript is key to crafting interactive and user-friendly web pages. At the heart of this lies the ability to tweak and tailor elements on the fly, which is where the setAttribute method comes into play. This powerful feature allows you to change or add attributes to HTML elements, giving you the flexibility to adjust their behavior or style as needed. 

Setattribute Javascript

This article will break down the essentials of setAttribute, from its syntax and parameters to its application in real-world scenarios. By the end, you'll have a solid grasp on using this method to make your web pages more dynamic and adaptable.


The setAttribute method in JavaScript is straightforward, yet powerful. It's used to add a new attribute to an HTML element or update the value of an existing attribute. The basic syntax looks like this:

element.setAttribute(attributeName, value);

Here, element is the DOM element you want to modify, attributeName is the name of the attribute you wish to add or update, & value is the new value you want to set for the attribute.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job


Diving deeper into the setAttribute function, it accepts two parameters:

  • attributeName: A string representing the name of the attribute you want to change or create. It's case-insensitive, meaning "class" & "CLASS" are treated the same.
  • value: The value you wish to set for the specified attribute. It must be a string. Even if you're setting a numerical value, it needs to be in string format, like "10" instead of just 10.

Return Value

An interesting aspect of setAttribute is that it doesn't have a return value. Its job is to perform an action, not to report back with data. Once you call setAttribute, it will either update the attribute or create a new one if it doesn't already exist, without providing any feedback.

The setAttribute method in JavaScript doesn't return a value in the traditional sense; its purpose is purely functional, aimed at modifying an attribute of an HTML element. When you invoke setAttribute, it either creates a new attribute with the specified value or updates the existing attribute's value. After the method executes, the change is reflected in the element's appearance or behavior on the web page, but the method itself does not provide any output or confirmation.

For instance, consider the following code snippet:

var buttonElement = document.getElementById("myButton");
buttonElement.setAttribute("disabled", "true");

In this example, the setAttribute method is used to disable a button element with the ID myButton by setting its disabled attribute to "true". Although the method effectively disables the button, it doesn't return any value to indicate success or failure. The absence of a return value means that if you need to check whether the attribute was successfully set, you'd have to explicitly query the element's attribute after the setAttribute call, like so:

if (buttonElement.getAttribute("disabled") === "true") {
    console.log("Button is successfully disabled.");
} else {
    console.log("Failed to disable the button.");

This approach allows you to verify the result of setAttribute, ensuring that your code behaves as expected without relying on a return value from the method itself.


To solidify your understanding of setAttribute, let's dive into some practical examples that demonstrate its versatility and power in web development.

Example 1: Changing the Style of an Element

Suppose you want to dynamically change the color and font size of a paragraph when a user clicks a button. Here's how you can achieve this with setAttribute:


<p id="myParagraph">This is a paragraph that will change style.</p>
<button onclick="changeStyle()">Change Style</button>


function changeStyle() {
  var paragraph = document.getElementById("myParagraph");
  paragraph.setAttribute("style", "color: blue; font-size: 20px;");

In this example, when the button is clicked, the changeStyle function is called. This function selects the paragraph by its ID and sets a new style attribute, changing the text color to blue and the font size to 20 pixels.

Example 2: Adding an Alt Text to an Image

If you have an image without an alt attribute and want to add one for accessibility reasons, you can use setAttribute like this:


<img id="myImage" src="image.jpg">


var image = document.getElementById("myImage");
image.setAttribute("alt", "A description of the image");

This code selects an image element and uses setAttribute to add an alt attribute with a descriptive text, improving accessibility.

Example 3: Setting Custom Data Attributes

HTML5 introduced custom data attributes, which are a powerful way to store extra information on HTML elements without using non-standard attributes or extra properties on the DOM. Here's how you can set a custom data attribute:


<div id="myDiv">Hover over me!</div>


var div = document.getElementById("myDiv");
div.setAttribute("data-tooltip", "This is a tooltip message");

This example adds a data-tooltip attribute to a div. You could use this attribute in your CSS or JavaScript to display a tooltip when the user hovers over the div.

Supported Browsers

The setAttribute method is widely supported across all major web browsers, ensuring that your web applications will function consistently for the vast majority of users. This includes:

  • Google Chrome
  • Mozilla Firefox
  • Apple Safari
  • Microsoft Edge
  • Opera

Even older versions of Internet Explorer (IE), starting from IE 8, offer support for setAttribute, albeit with some limitations and quirks in earlier versions. For instance, older versions of IE might not support setting certain attributes like class or style using setAttribute in the standard way; instead, you might need to use proprietary methods or workarounds, such as setting the className property directly for the class attribute or modifying the style property for inline styles.

However, given the decline in usage of older browsers and the advancement in web standards compliance in newer versions, these issues are becoming less relevant over time. Developers can confidently use setAttribute in modern web development projects with the expectation of broad compatibility.

Here's a quick example demonstrating the use of setAttribute in a way that's compatible across all modern browsers:

// Setting a 'title' attribute on a button element

var button = document.getElementById("myButton");
button.setAttribute("title", "Click me for more information");

In this code snippet, a button element is selected, and a title attribute is added using setAttribute. This title will appear as a tooltip when the user hovers over the button, providing additional information. This functionality is consistent across all current major browsers, making setAttribute a reliable tool in your web development toolkit.

Frequently Asked Questions

Can setAttribute add multiple attributes at once?

No, setAttribute is designed to handle one attribute at a time. If you need to set multiple attributes, you'll need to call setAttribute multiple times, once for each attribute you want to set or update.

Does setAttribute work with custom data attributes?

Yes, setAttribute works seamlessly with custom data attributes. You can use it to set or change data-* attributes, which are intended for storing custom data private to the page or application.

What happens if the specified attribute already exists?

If the attribute already exists on the element, setAttribute will update its value to the new value provided. If the attribute does not exist, setAttribute will create it with the specified value.


The setAttribute method in JavaScript is a powerful tool for dynamically modifying the attributes of HTML elements, enabling developers to create more interactive and responsive web applications. Through the examples and explanations provided, you've seen how setAttribute can be used to change styles, add accessibility features, and work with custom data attributes to enhance the user experience. Remember, while setAttribute is widely supported across all modern browsers, always ensure your web applications are tested across multiple platforms to guarantee a consistent and accessible experience for all users. With these insights and practical knowledge, you're well-equipped to leverage setAttribute in your web development projects, making your websites more dynamic and engaging.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
JavaScript Applications
Next article
OR(||) Logical Operator in JavaScript
Live masterclass