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ていますが、それは私が知る限り属性/コンテンツを保持しません。

注:なぜpにはhref?Cuz私は別のイベントにp戻る必要があります。a

4

6 に答える 6

19

より一般的な方法は次のとおりです。

// 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/

于 2010-09-08T09:07:49.470 に答える
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()また、通常、上記の例のように、特定のクラスに制限します。

于 2015-08-26T22:48:36.123 に答える
2

トリックを行うハッキー

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

デモ </p>

于 2010-09-08T09:03:15.913 に答える
0

私はそれを1つのプレーンな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));

}
于 2016-12-23T23:03:59.293 に答える
-1

これを試して:

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>');
于 2010-09-08T08:30:25.973 に答える