HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Remove attributes from an HTML element with JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptfromelementattributesremovewithhtml

Problem

Any attribute of an HTML element can be removed, using the Element.removeAttribute() method. This allows you to specify an attribute name, and remove it from the element.
But what if you want to remove all attributes from an HTML element? Element.attributes is a property that contains a list of all the attributes of an element.
In order to enumerate an element's attributes, Object.values() can be used. The array of attributes can then be iterated using Array.prototype.forEach() to remove each one from the element.

Solution

document.querySelector('img').removeAttribute('src');
// Removes the 'src' attribute from the <img> element


In order to enumerate an element's attributes, Object.values() can be used. The array of attributes can then be iterated using Array.prototype.forEach() to remove each one from the element.

Code Snippets

document.querySelector('img').removeAttribute('src');
// Removes the 'src' attribute from the <img> element
const removeAttributes = element =>
  Object.values(element.attributes).forEach(({ name }) =>
    element.removeAttribute(name)
  );

removeAttributes(document.querySelector('p.special'));
// The paragraph will not have the 'special' class anymore,
//  and all other attributes will be removed

Context

From 30-seconds-of-code: remove-attributes

Revisions (0)

No revisions yet.