Borislav Hadzhiev
Last updated: Jan 9, 2022
Check out my new book
To copy all attributes from one element to another:
Array.from()
method.forEach()
method to iterate over the array.setAttribute()
method to set each attribute on the target element.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style=" background-color: salmon; color: white; width: 150px; height: 150px; margin: 10px; " title="box" > Box content </div> <div id="another">Another Box</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
function copyAttributes(source, target) { return Array.from(source.attributes).forEach(attribute => { target.setAttribute( attribute.nodeName === 'id' ? 'data-id' : attribute.nodeName, attribute.nodeValue, ); }); } const box = document.getElementById('box'); const another = document.getElementById('another'); copyAttributes(box, another);
We created a reusable function that copies all the attributes from one element to another.
The
Element.attributes
property returns a Map
of strings representing the element's attributes.
const box = document.getElementById('box'); console.log(box.attributes); // 👉️ {0: id, 1: style, 2: title}
We used the Array.from method to get an array containing the attribute names.
const box = document.getElementById('box'); // 👇️ [id, style, title] console.log(Array.from(box.attributes));
The function we passed to the forEach method gets called with each element (attribute name) in the array.
On each iteration, we check if the attribute name is not equal to id
before
assigning it to the target element.
id
attribute have to be unique on the page, so it wouldn't make sense to copy the id
over.We used a
ternary operator
to check if the attribute's name is equal to id
.
The ternary operator is very similar to an if/else
statement.
If the expression to the left of the question mark evaluates to a truthy value, the value to the left of the colon is returned, otherwise the value to the right is returned.
The nodeName property returns the qualified name of the attribute.
The nodeValue property returns the value of the attribute.
We used the setAttribute method to set each attribute on the target element.
The setAttribute
method takes 2 parameters:
name
- the name of the attribute whose value is to be set.value
- the value to assign to the attribute.If I load the code from the example in my browser, I can see that the attributes have been copied over to the target element successfully.
Notice that the id
of the element remains the same, it hasn't been copied
over.
And the elements now look identical.
However, this wouldn't be the case if the source element has styles that are applied to it with an external style sheet.
If you need to copy ALL styles from one element to another, check out my other article - Copy all Styles from one Element to Another using JS.