Moaaz Bhnas
Moaaz Bhnas

Reputation: 1180

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');

Upvotes: 7

Views: 8655

Answers (4)

user11590849
user11590849

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

Ali Sheikhpour
Ali Sheikhpour

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

user3210641
user3210641

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

Nenad Vracar
Nenad Vracar

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

Related Questions