snippetjavascriptTip
Remove attributes from an HTML element with JavaScript
Viewed 0 times
javascriptfromelementattributesremovewithhtml
Problem
Any attribute of an HTML element can be removed, using the
But what if you want to remove all attributes from an HTML element?
In order to enumerate an element's attributes,
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> elementIn 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> elementconst 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 removedContext
From 30-seconds-of-code: remove-attributes
Revisions (0)
No revisions yet.