Handling Attributes of DOM element in JavaScript

June 20, 2020

Attribute

You can set additional information to a DOM element using attribute(name/value). For example id , class, title are common attribute which we set to most elements.

Methods Available to work with attributes

Method Description Syntax
setAttribute Add or Update an attribute setAttribute(name, value)
getAttribute get an attribute value getAttribute(name)
hasAttribute check if an element has attribute hasAttribute(name)
removeAttribute remove an attribute removeAttribute(name)

Let's consider we have an p element

<p id='para'>JavaScript Jeep</p>

getAttribute

The getAttribute() method returns the value of a specified attribute of the element.

var para = document.querySelector('p');
var id = pare.getAttribute('id'); // para

If the given attribute does not exist, the null will be returned.

var name = pare.getAttribute('class'); //null

setAttribute

The setAttribute method add an attribute to an element.

var para = document.querySelector('p');

// Adding a new Attribute
para.setAttribute('name', 'Julia Ann');
para.getAttribute('name'); // Julia Ann

If the attribute already exists, the value is updated, otherwise new attribute is added.

// updating value
pare.setAttribute('name', 'Mia');
para.getAttribute('name'); //Mia

hasAttribute

The hasAttribute method returns true if the specified element has the specified attribute , otherwise return false.

para.hasAttribute('name'); // true

para.hasAttribute('age'); // false

removeAttribute

The Element method removeAttribute removes the attribute with the specified name.

para.getAttribute('name'); // Mia

para.removeAttribute('name');

para.hasAttribute('name'); // false

Selecting an element based on attribute

document.querySelector('[attrName]');
// example
document.querySelector('[name]');

Selecting an element based on attribute name and value

document.querySelector('[attrName = "value"]')
// example
document.querySelector("[name='Mia']");

Please donate here, for making more tutorials.