简体   繁体   English

如何替换HTML标签和属性

[英]How to replace HTML tags and attributes

I have a section of code like this 我有一段这样的代码

<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

and I need to replace it with 我需要替换为

<h3>some text</h3>
<h3>some other text </h3>

Any help is appreciated. 任何帮助表示赞赏。

a javascript solution 一个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> 

The jquery solution: JSFiddle Demo jQuery解决方案: JSFiddle演示

$('p[class="xd"]').each(function(index,item){
    $(item).replaceWith("<h3>"+$(item).html()+"</h3>");  // keep the text, swap the tags
});

Thanks to Vishal Taj PM for showing a shorter solution: JSFiddle Demo 感谢Vishal Taj PM展示了一个较短的解决方案: JSFiddle演示

(for this case, there is no difference between text() and html() ) (在这种情况下, text()html()之间没有区别)

$('p.xd').each(function(){
  $(this).replaceWith("<h3>"+$(this).text()+"</h3>")  
});

If you are looking for a solution with Jquery you can use replaceWith(). 如果您正在寻找使用Jquery的解决方案,则可以使用replaceWith()。 it will replace existing tag with new one. 它将用新标签替换现有标签。

please find the code snippet below. 请在下面找到代码段。

 $('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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM