Removing All HTML Element Attributes at Once

 + how to do it using jQuery

Sometimes you are required to remove all attributes from HTML element. There is no native JavaScript method to achieve this. However, we can definitely do that with a single loop, iterating over HTML element attributes removing each on the way.

var element = document.body;
for (var i = element.attributes.length - 1; i >= 0; i--){
  element.removeAttribute(element.attributes[i].name);
}

It is important to point out that we have to loop the array in a reverse direction (starting with the last item) to avoid getting an error due to the changing length of the array while removing items. When starting removing from the last item, updated array length doesn't matter, because the next item in the loop is a previous one.

Remove All Attributes at Once Using jQuery

For jQuery users, probably the best implementation would be to extend its existing .removeAttr() function making it accept zero parameters to remove all attributes from each element in a set.

var removeAttr = jQuery.fn.removeAttr;
jQuery.fn.removeAttr = function() {

  if (!arguments.length) {
    this.each(function() {
      for (var i = this.attributes.length - 1; i >= 0; i--) {
        jQuery(this).removeAttr(this.attributes[i].name);
      }
    });

    return this;
  }

  return removeAttr.apply(this, arguments);
};

Now you can call .removeAttr() without parameters to remove all attributes from the element:

$('body').removeAttr();

I have also published this jQuery extension answering a question on StackOverflow. Feel free to vote up if you find it useful.


To sum up the logic, you can safely remove items from any array while iterating it in a reverse direction. Reverse looping will assure that array length decreased on every removal is not going to cause you errors.

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
for (var i = arr.length - 1; i >= 0; i--) {
  arr.splice(i, 1);
}
#html #javascript #jquery #attributes #reverse loop