December 24, 2018

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' ) const oldEl = e . querySelector ( '.old-el' ) ; [ ... oldEl . attributes ] . map ( ( { name , value } ) => { newEl . setAttribute ( name , value ) } ) 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: