[英]How to replace HTML tags and attributes
我有一段這樣的代碼
<p style="position:absolute;top:-866px;left:1550px;white-space:nowrap" class="xd">some text
<p style="position:absolute;top:-866px;left:1550px;white-space:nowrap" class="xd">some other text
我需要替換為
<h3>some text</h3>
<h3>some other text </h3>
任何幫助表示贊賞。
一個javascript解決方案
<script>
document.getElementsByClassName("xd")[0].outerHTML="<h3>some text</h3>"
</script>
<p style="position:absolute;top:-866px;left:1550px;white-space:nowrap" class="xd">some text</p> <p style="position:absolute;top:-866px;left:1550px;white-space:nowrap" class="xd">some text</p> <script> var all_p = document.getElementsByClassName("xd"); while (all_p.length != 0) { all_p[0].outerHTML = "<h3>some text</h3>"; } </script>
jQuery解決方案: JSFiddle演示
$('p[class="xd"]').each(function(index,item){
$(item).replaceWith("<h3>"+$(item).html()+"</h3>"); // keep the text, swap the tags
});
感謝Vishal Taj PM展示了一個較短的解決方案: JSFiddle演示
(在這種情況下, text()
和html()
之間沒有區別)
$('p.xd').each(function(){
$(this).replaceWith("<h3>"+$(this).text()+"</h3>")
});
如果您正在尋找使用Jquery的解決方案,則可以使用replaceWith()。 它將用新標簽替換現有標簽。
請在下面找到代碼段。
$('p.xd').each(function(){ $(this).replaceWith("<h3>"+$(this).text()+"</h3>") });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p style="position:absolute;top:-866px;left:1550px;white-space:nowrap" class="xd">some text</p> <p style="position:absolute;top:-866px;left:1550px;white-space:nowrap" class="xd">some other text</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.