How to Get and Set Attributes with Javascript

Just like jQuery’s $.attr() method, there are native browser methods that can get and set attributes of an element.

Checking whether an Attribute Exists

The hasAttribute method can tell whether the element has the given attribute or not.

A true is returned if the element has the attribute, and false otherwise.

if(document.querySelector("#container").hasAttribute('data-post-id')) {
	console.log('Attribute present');
else {
	console.log('Attribute not present');

Checking whether Element has Any Attributes

The hasAttributes method tells whether the element has at least one attribute present (it can be any attribute).

See also  Animated Directional Arrows In CSS - Arrows.css

A true is returned if the element has any attributes present, and false if the element has no attributes at all.

if(document.querySelector("#container").hasAttributes()) {
	console.log('At least one attribute present');
else {
	console.log('No attributes present');

Getting the Value of an Attribute

The getAttribute method returns the value of the attribute.

var post_id = document.querySelector("#container").getAttribute('data-post-id');

If the attribute is not existing, then null or a blank value “” will be returned. There are confusions among specifications whether to return null or a blank. To be on the safer side, it is best to first check whether the attribute is existent (using hasAttribute), and then getting its value. Otherwise a blank value may be mistaken for its value.

See also  Radio Buttons Using HTML CSS

Getting All Attributes of the Element

The getAttributeNames method returns an array of all attribute names (values are not returned). If element has no attributes then an empty array is returned.

Once the attribute name is retrieved, its value can be found with getAttribute.

// all attributes
var attributes = document.querySelector("#container").getAttributeNames();
var attribute_value;

// show values of all attributes
for(var i=0; i<attributes.length; i++) {
	attribute_value = document.querySelector("#container").getAttribute(attributes[i]);

Setting the Value of an Attribute

The setAttribute method sets the value of the attribute. If the attribute is not existing then it is added.

document.querySelector("#container").setAttribute('data-post-id', '12');

Removing an Attribute

The removeAttribute method removes the attribute from the element. If the attribute does not exist, no error is thrown.


Leave a Reply

Your email address will not be published. Required fields are marked *