From 69a116d0aa4d2513d20ecbc63719e8ac58e4bc56 Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Sat, 16 Jul 2022 18:04:16 +0300 Subject: [PATCH] Add removeAttributes snippet --- snippets/removeAttributes.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 snippets/removeAttributes.md diff --git a/snippets/removeAttributes.md b/snippets/removeAttributes.md new file mode 100644 index 00000000000..c08fdcec425 --- /dev/null +++ b/snippets/removeAttributes.md @@ -0,0 +1,25 @@ +--- +title: Remove attributes +tags: browser +expertise: beginner +cover: blog_images/new-york.jpg +author: chalarangelo +firstSeen: 2022-07-20T05:00:00-04:00 +--- + +Removes all attributes from an HTML element. + +- Use `Element.attributes` and `Object.values()` to get all the attributes of the element. +- Use `Array.prototype.forEach()` and object destructuring to get the name of each attribute and `Element.removeAttribute()` to remove it from the element. + +```js +const removeAttributes = element => + Object.values(element.attributes).forEach(({ name }) => + element.removeAttribute(name) + ); +``` + +```js +removeAttributes(document.querySelector('p.special')); +// The paragraph will not have the 'special' class anymore +```