Remove All Attributes From an Element in JavaScript

- 1 minute read

This JavaScript function will accept a given HTML element and remove all of its attributes:

const removeAttributes = (element) => {
    while (element.attributes.length > 0) {
        element.removeAttribute(element.attributes[0].name);
    }
};

If you don’t want to use a while loop, here is an alternative removeAttributes function:

const removeAttributes = (element) => {
    for (let i = 0; i < element.attributes.length; i++) {
        element.removeAttribute(element.attributes[i].name);
    }
};

Regardless of which variant of the removeAttributes function you chose, here is some example usage:

const element = document.getElementById(`example`);

removeAttributes(element);

In the above example, an element with an ID of example is stripped of all its attributes.

Link to this section Conclusion

I’ve found this to be an exceedingly simple yet exceedingly useful function, and I hope it helped you out as well!