更改标签但保留属性和内容 -- jQuery/Javascript

9
<a href="page.html" class="class1 class2" id="thisid">Text</a>

更改为

<p href="page.html" class="class1 class2" id="thisid">Text</p>

我熟悉jQuery的replaceWith, 但据我所知,它不会保留属性/内容。
注意:为什么

会有一个href?因为我需要在另一个事件中将

改回标签。


为什么不直接读取属性(href、class和id),然后在替换后重新分配呢? - Vikash
6个回答

20

这里有一种更通用的方法:

// 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);
});

你可以在这里尝试代码:http://jsfiddle.net/tTAJM/


1
好的解决方法,但当标记内含有另一个相等符号时出现了错误:<a><a></a></a>(转换为<p><a></p></a>)。我进行了修复,将"//Replace closing tag"部分更改为如下内容:regex = new RegExp('</' + this.tagName + '>$', 'i');newTag = newTag.replace(regex, '</' + replacementTag + '>'); - Michael Aguilar

9
这是我在jquery中使用的替换html标签的方法:
// 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());
  });

});

通常情况下,我会将其限制在特定的类别中,例如上面的示例中的$('a.class1').each(function()


这太棒了,Seth。在我看来,这是最干净、最容易实现的方法。 - Nathan

8

为了将来的可重用性,最好创建jQuery插件:

(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);

使用方法:

// Replace given object tag's name
$('a').replaceTagName("p");

示例:JSFiddle

1
你有一个错误,请将 g[h - 1] = k 更改为 g[h] = k - Serhii Maksymchuk
请注意,如果您将其用于单个对象,则需要重新分配它,例如 a = a.replaceTagName("p") - sox with Monica

2

使用hacky方法来完成任务

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


+1 好主意,你确定表达式中需要使用 g 标志吗?我猜只需要替换一次,是吧? - sharat87

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));
     }
}

如果您只想替换特定的标签,只需删除for循环即可:
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));

}

-2

试一下这个:

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>');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接