Get, Set and Remove Attributes with JavaScript

09/20/2021

Contents

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.

Attribute Value
type text
id myid
name myname
minlength 8
placeholder Password

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

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

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