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');
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');
Share
Improve this question
edited May 26, 2018 at 10:37
Moaaz Bhnas
asked May 26, 2018 at 10:34
Moaaz BhnasMoaaz Bhnas
1,1707 gold badges20 silver badges41 bronze badges
1
-
2
You could set its
outerHTML
, but it would really be best simply to callremoveAttribute
twice, or create your own helper function that accepts multiple arguments – CertainPerformance Commented May 26, 2018 at 10:37
4 Answers
Reset to default 10You 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');
Jquery solution: space separated attributes like image.removeAttr('src alt')
should work.
Edit: using pure Javascript you can loop through an array using removeAttribute:
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 === 'plete') {
rmattr();
} else {
addEventListener('load', rmattr);
}
})();