How to Copy Attributes from One Element to Another
I was trying to copy all attributes from one element to another and I found a great article online that provided a function that I used in one of my projects.
Post: https://bobbyhadz.com/blog/javascript-copy-all-attributes-from-one-element-to-another
index.html
<!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>
index.js
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);