[英]Replace all <a> with <span> tag in a string : Javascript
[英]Replace all span tag in webpage
我有一個問題,因為我想將頁面中的所有跨度替換為標簽b。
這是演示,但很糟糕。 要更改所有跨度,我必須單擊按鈕上的2倍
jQuery的:
$('#myButton').click(function(){
$("span").replaceWith(function(){
return $("<b>" + $(this).html() + "</b>");
});
});
HTML:
<span>fdfdfd <span>hytrytryrt</span> fdfdfdf</span>
<button id="myButton">Change my link to a span</button>
這里是鏈接:
我只是有一個主意!,嘗試reverse
元素集合,然后調用.replaceWith()
$('#myButton').click(function(){
$($("span").get().reverse()).replaceWith(function(){
return $("<b>" + $(this).html() + "</b>");
});
});
<span>fdfdfd <span>hytrytryrt</span> fdfdfdf</span>
<button id="myButton">Change my link to a span</button>
$('#myButton').click(function(){
$("span").replaceWith(function(){
return $("<b>" + $(this).text() + "</b>");
});
});
演示:
首先,您的標記無效。 它應該是:
<span>fdfdfd</span> <span>hytrytryrt</span> <span>fdfdfdf</span>
並使用b更改跨度:
$('#myButton').click(function(){
$("span").each(function(){
$(this).replaceWith("<b>" + $(this).html() + "</b>");
});});
像這樣更改您的html
$('#myButton').on('click',function(){
$("span").replaceWith(function(){
return $("<b>" + $(this).text() + "</b>");
});
});
注意
在 jQuery 1.9 之前 ,如果集合中的第一個節點未連接到文檔,則.replaceWith()會嘗試在當前jQuery集合中添加或更改節點,在這種情況下,它們將return a new jQuery set
而不是original set.
該方法可能返回也可能未返回新結果,具體取決於其參數的數量或連接性!
從jQuery 1.9開始 , .replaceWith()
始終return the original unmodified set
。 嘗試在沒有父節點的節點上使用這些方法沒有任何effect—that
即,集及其所包含的節點都不會更改。
這最好是使用純JavaScript而不使用jQuery來完成。 您只需獲取所有span
元素,然后在DOM中將它們中的每個替換為您創建的b
元素,即可將span
的內容分配給它。
<button id="myButton" onclick="chg()">Change span to b</button>
<script>
function chg() {
var spans = document.getElementsByTagName('span');
for(var i = spans.length - 1; i >= 0; i--) {
var b = document.createElement('b');
b.innerHTML = spans[i].innerHTML;
spans[i].parentNode.replaceChild(b, spans[i]);
}
}
</script>
for
循環“向后”運行,因為getElementsByTagName
方法以樹順序返回元素的實時集合。 因此,如果從索引0開始,則將(在簡單示例中)首先處理外部span
元素,當到達內部span
元素時,該集合將縮小,以使其只有一個成員(索引為0),而內部span
因此不會被處理。
此代碼不復制span
元素的任何屬性。 如果有要保留的屬性,請添加用於復制它們的代碼。
PS我懷疑真正的問題與提出的問題本質上是不同的,因為將所有span
元素更改為b
元素僅在相當特殊的情況下才有意義,並且問題中的按鈕文本“ Change my link to a span”與問題中的按鈕文本不匹配。描述或代碼片段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.