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

时间:2010-09-08 08:23:08

标签: javascript jquery dom-manipulation replacewith

文本

更改为

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

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

注意:为什么p会有href?我需要在另一个事件中将p更改回a

5 个答案:

答案 0 :(得分: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);
});

您可以在此处尝试代码:http://jsfiddle.net/tTAJM/

答案 1 :(得分: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);

用法:

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

示例:JSFiddle

答案 2 :(得分: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

答案 3 :(得分:0)

试试这个:

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

答案 4 :(得分:0)

我把它变成了一个普通的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));
     }
}

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

}