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

Kyl*_*yle 7 javascript jquery dom-manipulation replacewith

文本

变成

<p href="page.html" class="class1 class2" id="thisid">Text</p>
Run Code Online (Sandbox Code Playgroud)

我熟悉jQuery,replaceWith但据我所知,这并没有保留属性/内容.

注意:为什么p会有href?因为我需要改pa另一个事件.

小智 18

这是一个更通用的方法:

// 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);
});
Run Code Online (Sandbox Code Playgroud)

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

  • 很好的解决方案,但当标签内部有另一个相同的内容时,我遇到了一个错误:`&lt;a&gt;&lt;a&gt;&lt;/a&gt;&lt;/a&gt;`(转换为`&lt;p&gt;&lt;a&gt;&lt;/p&gt;&lt;/a&gt;` ),我修复了将“//替换结束标记”部分更改为: `regex = new RegExp('&lt;/' + this.tagName + '&gt;$', 'i');newTag = newTag.replace(regex, '&lt;/' + 替换标签 + '&gt;');` (2认同)

Set*_*ley 8

这是我用来替换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());
  });

});
Run Code Online (Sandbox Code Playgroud)

我通常也会将其限制为特定的类,$('a.class1').each(function()例如上面的例子.


Ili*_*sev 6

最好为未来的可重用性创建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);
Run Code Online (Sandbox Code Playgroud)

用法:

// Replace given object tag's name
$('a').replaceTagName("p");
Run Code Online (Sandbox Code Playgroud)

示例:JSFiddle


Moi*_*man -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>');
Run Code Online (Sandbox Code Playgroud)