views:

38

answers:

3

Hello! How can you get:

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

+1  A: 

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>');
Moin Zaman
awesome! thanks!
Emile
+2  A: 

hacky that do the trick

var p = $('a').wrapAll('<div class="replace"></div>');

var a = $('div').map(function(){
    return this.innerHTML;
}).get().join(' ');


$('div.replace').html(a.replace(/<a/g,'<p').replace(/a>/g,'p>'));

demo

Reigel
+1 Thanks Reigel! This looks like another great answer
Emile
+1 Nice idea, You sure the `g` flag is necessary in the expressions? I guess only one replacement should be done eh?
Shrikant Sharat
+2  A: 

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/

softcr
cool! thank you!
Emile