<a href="page.html" class="class1 class2" id="thisid">Text</a>
changed to
<p href="page.html" class="class1 class2" id="thisid">Text</p>
I'm familiar with jQuery's replaceWith
but that doesn't keep attributes/content as far as I know.
Note: Why would p have a href
? Cuz I need to change p
back to a
on another event.
jQuery attr() Method When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
To change the element tag name in JavaScript, simply need to make a new element and move over all the elements so you keep onclick handlers and such, and then replace the original thing.
You can add attributes using attr like so: $('#someid'). attr('name', 'value'); However, for DOM properties like checked , disabled and readonly , the proper way to do this (as of JQuery 1.6) is to use prop .
To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.
It's better to create jQuery plugin for future re-usability:
(function (a) {
a.fn.replaceTagName = function (f) {
var g = [],
h = this.length;
while (h--) {
var k = document.createElement(f),
b = this[h],
d = b.attributes;
for (var c = d.length - 1; c >= 0; c--) {
var j = d[c];
k.setAttribute(j.name, j.value)
}
k.innerHTML = b.innerHTML;
a(b).after(k).remove();
g[h - 1] = k
}
return a(g)
}
})(window.jQuery);
Usage:
// Replace given object tag's name
$('a').replaceTagName("p");
Example: JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With