Handling Attributes of DOM element in JavaScript

June 20, 2020


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>


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


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


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

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

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


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

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


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

Selecting an element based on attribute

// example

Selecting an element based on attribute name and value

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

Please donate here, for making more tutorials.