Skip to content

Instantly share code, notes, and snippets.

@efrigoli
Created January 9, 2025 20:14
Show Gist options
  • Save efrigoli/392868ea547feae8f27a31d8645c664c to your computer and use it in GitHub Desktop.
Save efrigoli/392868ea547feae8f27a31d8645c664c to your computer and use it in GitHub Desktop.
This code provides a simple jQuery function for converting an HTML DOM element into a different type of HTML DOM element while retaining the original elements attributes.
/*
* All code is intended as a learning example only and will require modification to function properly based on the project needs.
*/
jQuery(document).ready(function ($) {
// Usage example: converting a mobile menu toggile from a span to a button element.
$('span.mobile-menu-toggle').convertElement('button');
// Converting a DOM element into a specified new type of element
$.fn.convertElement = function (newType) {
// Creating an array to store attributes.
var atts = {};
// Looping through the attributes of the element and storing them in the atts array.
$.each(this[0].attributes, function (idx, attr) {
atts[attr.nodeName] = attr.nodeValue;
});
// Replacing the current element with the new element, maintaining the original attributes.
this.replaceWith(function () {
return $('<' + newType + '/>', atts).append($(this).contents());
});
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment