Get, Set and Remove Attributes with JavaScript

Web Design & Web Development

In this article, I will introduce how to get, set and remove attributes with JavaScript.

What are HTML Attributes?

HTML elements can have attributes that define additional characteristics or properties.

Let's take a look at an example of the attributes usages:

<input type="text" id="myid" name="myname" minlength="8" placeholder="Password">

In the above example, the relationship between attributes and values inside the <input> element ​​is shown in the table below.

AttributeValue
typetext
idmyid
namemyname
minlength8
placeholderPassword
Sponsored links

getAttribute()

The getAttribute method returns the value of a specified attribute on the element.
If the attribute does not exist, then null or "" (the empty string) will be returned.

const attributeValue = element.getAttribute('attributeName');

Example

HTML
<input type="text" id="myid" placeholder="Password">
JavaScript
const element = document.getElementById('myid');

const inputId = element.getAttribute('id');
console.log(inputId); // myid

const inputType = element.getAttribute('type');
console.log(inputType); // text

const inputPlaceholder = element.getAttribute('placeholder');
console.log(inputPlaceholder); // "Password"

const test = element.getAttribute('test');
console.log(test); // null
Sponsored links

setAttribute()

The setAttribute method sets the value of an attribute on the specified element. If the attribute already exists, the value is updated.

element.setAttribute('attributeName', 'attributeValue');

Example

HTML
<input type="text" id="myid" maxlength="16">
JavaScript
let inputMinlength = element.getAttribute('minlength');
console.log(inputMinlength); // null

element.setAttribute('minlength','8');

inputMinlength = element.getAttribute('minlength');
console.log(inputMinlength); // 8

let inputMaxlength = element.getAttribute('maxlength');
console.log(inputMaxlength); // 16

element.setAttribute('maxlength','24');

inputMaxlength = element.getAttribute('maxlength');
console.log(inputMaxlength); // 24
Sponsored links

removeAttribute()

The removeAttribute method removes the specified attribute from the element.

element.removeAttribute('attributeName');

Example

HTML
<input type="text" id="myid" maxlength="16">
JavaScript
let inputMaxlength = element.getAttribute('maxlength');
console.log(inputMaxlength); // 16

element.removeAttribute('maxlength');

inputMaxlength = element.getAttribute('maxlength');
console.log(inputMaxlength); // null