Skip to main content
Home

Copy attributes from an element

Just discovered a nice way of copying all the html attributes from one DOM element to another, figured I'd write this trick down for keeping it around.

const newEl = document.createElement('div');

// <span class="old" data-test="test"></span>
const oldEl = e.querySelector('.old-el');

// Spread all attributes from old element to the new one
[...oldEl.attributes].map(({ name, value }) => {
  newEl.setAttribute(name, value);
});

// <div class="old" data-test="test"></div>
console.log(newEl);

Note: oldEl.attributes is not a real array, it's an NamedNodeMap. This is why we need to create a new array by spreading all items into it. Each entry has a name and a value, which we gently pass to Element.setAttribute().

Reference:

Profile picture

Andrei Glingeanu's notes and thoughts. You should follow him on Twitter, Instagram or contact via email. The stuff he loves to read can be found here on this site or on goodreads. Wanna vent or buy me a coffee?