JSFiddle - React, Tailwind, and code Playground
by roeburg
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css">
<h1>Hover Each Element To View Attributes</h1>
<hr />
<p class="sourceElement" data-attr1="1" data-attr2="2" data-attr3="13">This is the source element.</p>
<p class="destinationElement">This is the destination element.</p>
<button>Click Here To Copy Attributes from Source to Destination</button>
CSS
p:hover {
background: #e1e1e1;
border-top: 1px solid #d0d0d0;
}
p, button{
padding:20px;
margin:20px;
}
.modified{
color: red;
}
JavaScript
(function ($) {
// Define the function here
$.fn.copyAllAttributes = function (sourceElement) {
// 'that' contains a pointer to the destination element
var that = this;
// Place holder for all attributes
var allAttributes = ($(sourceElement) && $(sourceElement).length > 0) ?
$(sourceElement).prop("attributes") : null;
if (allAttributes && $(that) && $(that).length == 1) {
$.each(allAttributes, function () {
// Ensure that class names are not copied but rather added
if(this.name == "class"){
$(that).addClass(this.value);
} else {
that.attr(this.name, this.value);
}
});
}
return that;
};
})(jQuery);
$(function(){
/// **** USAGE *****
$("button").click(function (){
$(".destinationElement").copyAllAttributes($(".sourceElement"));
$(".destinationElement").addClass("modified");
});
/// **** USAGE *****
// Helper Function To View Available Attributes
$("p").mouseover(function (e) {
// Element
var element = $(e.target);
// Get All Attributes
var allAttributes = $(element).prop("attributes");
// For each attribute collect KVP's
var kvpString = "";
$.each(allAttributes, function (iindex, ielement) {
kvpString += ("[" + iindex + "]: " + this.name + " : " + this.value + " <br />");
});
// Display Kvp
toastr.success(kvpString, "Highlighted Element's Attributes/Values");
});
});