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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3665820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:52:26  来源:igfitidea点击:

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

javascriptjquerydom-manipulationreplacewith

提问by Kyle

Text

文本

changed to

变成

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

I'm familiar with jQuery's replaceWithbut that doesn't keep attributes/content as far as I know.

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

Note: Why would p have a href? Cuz I need to change pback to aon another event.

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

采纳答案by Moin Zaman

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

回答by softcr

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/

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

回答by Seth McCauley

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

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

});

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

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

回答by Ilia Rostovtsev

It's better to create jQuery plugin for future re-usability:

最好为将来的可重用性创建 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);

Usage:

用法:

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

Example: JSFiddle

示例:JSFiddle

回答by Reigel

hacky that do the trick

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?

演示

回答by WIPocket

I made it into one plain-javascript function:

我把它变成了一个普通的javascript函数:

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:

如果只想替换特定标签,只需删除 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));

}