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

6

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

Familiarize answered 8/9, 2010 at 8:23 Comment(1)
Why don't you just read the attributes (href, class and id) and then reassign it after replacement?Bendicty
U
-2

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>');
Unilobed answered 8/9, 2010 at 8:30 Comment(0)
E
20

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/

Expiratory answered 8/9, 2010 at 9:7 Comment(1)
Good solution but i got a bug when the tag have another equal inside: <a><a></a></a> (converto to <p><a></p></a>), I fixed changing the "//Replace closing tag" section to this: regex = new RegExp('</' + this.tagName + '>$', 'i');newTag = newTag.replace(regex, '</' + replacementTag + '>');Wagonlit
P
9

Here is a method I use to replace html tags in jquery:

// Iterate over each element and replace the tag while maintaining attributes
$('a').each(function() {

  // Create a new element and assign it attributes from the current element
  var NewElement = $("<p />");
  $.each(this.attributes, function(i, attrib){
    $(NewElement).attr(attrib.name, attrib.value);
  });

  // Replace the current element with the new one and carry over the contents
  $(this).replaceWith(function () {
    return $(NewElement).append($(this).contents());
  });

});

I would also typically restrict it to a specific class, such as $('a.class1').each(function() for the example above.

Parasynapsis answered 26/8, 2015 at 22:48 Comment(1)
This is excellent, Seth, the cleanest method and easiest to implement in my opinion.Armanda
C
8

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

Counterfeit answered 27/3, 2016 at 12:7 Comment(2)
You have a bug, change g[h - 1] = k to g[h] = kWendiewendin
Note that if you use it on a single object, you need to reassign it like a = a.replaceTagName("p")Krummhorn
W
2

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

Windle answered 8/9, 2010 at 9:3 Comment(1)
+1 Nice idea, You sure the g flag is necessary in the expressions? I guess only one replacement should be done eh?Gingham
C
2

I made it into one plain-javascript function:

function ReplaceTags(Original, Replace){
     var oarr = document.getElementsByTagName(Original);
     for(i=0; oarr.length < i; i++){
var html = oarr[i].outerHTML;
oarr[i].outerHTML = (html.replace(Original, Replace));
     }
}

If you want to replace only a specific tag, just delete the for loop:

function ReplaceTag(Original, Replace, customi){ 
// If customi = 0 the first appearance will get replaced
var i = customi;
    if(i == undefined)
     i=0;
var oarr = document.getElementsByTagName(Original);
var html = oarr[i].outerHTML;
oarr[i].outerHTML = (html.replace(Original, Replace));

}
Creon answered 23/12, 2016 at 23:3 Comment(0)
U
-2

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>');
Unilobed answered 8/9, 2010 at 8:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.