Search code examples
javascriptjquerydom-manipulationreplacewith

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


<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.


Solution

  • try this:

    var $a = $('a#thisid');
    var ahref = $a.attr('href');
    var aclass = $a.attr('class');
    var aid = $a.attr('id');
    var atext = $a.text();
    $a.replaceWith('<p href="'+ ahref +'" class="'+ aclass +'" id="'+ aid+'">'+ atext +'</p>');