Element

Element.prototype.setAttribute

Sets the value of an attribute on the specified element, adding it if it does not already exist

Syntax

JavaScript
element.setAttribute(name, value)

Parameters

ParameterTypeDescription
namestringThe name of the attribute
valuestringThe value to assign

Return Value

undefined

Examples

Basic Usage
const link = document.querySelector('a')!
link.setAttribute('href', 'https://example.com')
link.setAttribute('target', '_blank')
Practical Example
const img = document.createElement('img')
img.setAttribute('src', '/photo.jpg')
img.setAttribute('alt', 'A photo')
img.setAttribute('loading', 'lazy')
Advanced Usage
function setDataAttrs(el: HTMLElement, data: Record<string, string>) {
  Object.entries(data).forEach(([key, val]) => {
    el.setAttribute(`data-${key}`, val)
  })
}

Understanding Element.prototype.setAttribute

The Element.prototype.setAttribute method in JavaScript sets the value of an attribute on the specified element, adding it if it does not already exist. It belongs to the Element object and is one of the most widely used methods for working with element values in modern JavaScript and TypeScript applications.

The method signature is element.setAttribute(name, value). It accepts 2 parameters: name, value. When called, it returns undefined. Understanding when and how to use setAttribute() helps you write more expressive, readable code.

Common use cases for Element.prototype.setAttribute include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like dom-getattribute, dom-removeattribute, dom-hasattribute, enabling you to chain operations together for complex data manipulation pipelines.

Browser support for Element.prototype.setAttribute is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.

Browser Compatibility

Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.

Related Methods

More Element Methods

Other methods in the Element object

Related Tools

More Element Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.