This is mostly a note for myself, but thought it might come in handy for some: Sometimes you need to transfer or copy DOM attributes from one element to another (as opposed to copying the whole element with cloneNode). Luckily, there’s the handy attributes object:

querySelector('iframe').attributes
Code language: JavaScript (javascript)

In my case, I needed to transfer all attributes to my new element, so I wrote myself a little helper function:

function copyAttrs(src, target) { for(let attr of src.attributes) { target.setAttribute(attr.name, attr.value); } }
Code language: JavaScript (javascript)

You can now use it like this:

let elemA = querySelector('.elem-a'); let elemB = querySelector('.elem-b'); copyAttrs(elemA, elemB);
Code language: JavaScript (javascript)

Update (July 30, 2019): According to Domenic (thanks!), .attributes should be avoided in performance critical scenarios (it forces the creation of Attr objects which otherwise can stay hidden). Instead, use getAttributeNames() + (get|set)Attribute(NS).


Reply with a tweet or leave a Webmention. Both will appear here.