Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove multiple attributes from a node?

I have this image element:

<img class="cat" src="img/tom.png" alt="Cat">

I want to remove both src and alt attributes at once.
I expected removeAttribute() method to take multiple arguments, but it doesn't.

Is there another way to do so other than this repetitive code:

image.removeAttribute('src');
image.removeAttribute('alt');
like image 425
Moaaz Bhnas Avatar asked Dec 14 '22 16:12

Moaaz Bhnas


2 Answers

You could make a function that takes an element and attributes you want to remove.

function removeAttributes(element, ...attrs) {
  attrs.forEach(attr => element.removeAttribute(attr))
}

removeAttributes(document.querySelector('img'), 'src', 'alt')
<img class="cat" src="img/tom.png" alt="Cat">

If you want to call it on DOM element you could extend Element prototype.

Element.prototype.removeAttributes = function(...attrs) {
  attrs.forEach(attr => this.removeAttribute(attr))
}

document.querySelector('img').removeAttributes('src', 'alt')
<img class="cat" src="img/tom.png" alt="Cat">
like image 194
Nenad Vracar Avatar answered Dec 16 '22 04:12

Nenad Vracar


Not sure it makes it any better but you could probably do something like this:

['alt', 'src'].forEach(attribute => image.removeAttribute(attribute));

or create a general remove attributes function:

const removeAttributes = (element, ...attributes) => attributes.forEach(attribute => element.removeAttribute(attribute));

which you would call like this:

removeAttributes(image, 'alt', 'src');
like image 21
user3210641 Avatar answered Dec 16 '22 04:12

user3210641