Change the tag but keep the attributes and content -- jQuery/Javascript

Kyle picture Kyle · Sep 8, 2010 · Viewed 12k times · Source
<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.

Answer

softcr picture softcr · Sep 8, 2010

Here is a more generic method:

// New type of the tag
var replacementTag = 'p';

// Replace all a tags with the type of replacementTag
$('a').each(function() {
    var outer = this.outerHTML;

    // Replace opening tag
    var regex = new RegExp('<' + this.tagName, 'i');
    var newTag = outer.replace(regex, '<' + replacementTag);

    // Replace closing tag
    regex = new RegExp('</' + this.tagName, 'i');
    newTag = newTag.replace(regex, '</' + replacementTag);

    $(this).replaceWith(newTag);
});

You can try the code here: http://jsfiddle.net/tTAJM/