30秒学会 JavaScript 片段 · 2023年2月23日

30秒学会 JavaScript 片段 – Remove attributes from an HTML element with JavaScript

Any attribute of an HTML element can be removed, using the Element.removeAttribute() method. This allows you to specify an attribute name, and remove it from the element.

代码实现

document.querySelector('img').removeAttribute('src');
// Removes the 'src' attribute from the <img> element

But what if you want to remove all attributes from an HTML element? Element.attributes is a property that contains a list of all the attributes of an element.

In order to enumerate an element’s attributes, Object.values() can be used. The array of attributes can then be iterated using Array.prototype.forEach() to remove each one from the element.

使用样例

const removeAttributes = element =>
  Object.values(element.attributes).forEach(({ name }) =>
    element.removeAttribute(name)
  );

removeAttributes(document.querySelector('p.special'));
// The paragraph will not have the 'special' class anymore,
//  and all other attributes will be removed

翻译自:https://www.30secondsofcode.org/js/s/remove-attributes