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');
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">
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With