Reputation: 1180
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');
Upvotes: 7
Views: 8655
Reputation:
Here's how I did it --
(() => {
'use strict';
let token = 'src|alt';
if (token === '' || token === '{{1}}') { return; }
let tokens = token.split(/\s*\|\s*/);
let selector = 'img';
if (selector === '' || selector === 'img') {
selector = `[${tokens.join('],[')}]`;
}
let rmattr = () => {
let elements = document.querySelectorAll(selector);
for ( let element of elements ) {
for (let attr of tokens) {
element.removeAttribute(attr);
}
}
};
if (document.readyState === 'loading' || document.readyState === 'interactive' || document.readyState === 'complete') {
rmattr();
} else {
addEventListener('load', rmattr);
}
})();
Upvotes: 0
Reputation: 11096
Jquery solution: space separated attributes like image.removeAttr('src alt')
should work.
Edit: using pure Javascript you can loop through an array using removeAttribute:
Upvotes: 0
Reputation: 1631
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');
Upvotes: 8
Reputation: 122087
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">
Upvotes: 10