我希望使用JavaScript替换H2 Tag的H2标签。
请帮助我!!
提前致谢,
<h3 id="replace_h3_tag_by_h2_tag">This is H3 Heading</h3>
<button type="button" onclick="changeHTMLTag()">I want to Replace H3 Tag by H2 Tag Using JavaScript</button>
<script>
function changeHTMLTag()
{
//Help Me
}
</script>
答案 0 :(得分:1)
只需更改H3标签的outerHTML,如下所示:
function changeHTMLTag()
{
var el = document.querySelector('#replace_h3_tag_by_h2_tag');
el.outerHTML = '<h2>' + el.innerHTML + '</h2>';
}
&#13;
<h3 id="replace_h3_tag_by_h2_tag">This is H3 Heading</h3>
<button type="button" onclick="changeHTMLTag()">I want to Replace H3 Tag by H2 Tag Using JavaScript</button>
&#13;
PS:使用类或数据更改 - 而不是id来更改多个
<h3 data-change-this>Change me!</h3>
<h3 class="change-this">Change me!</h3>
然后使用
document.querySelectorAll('[change-this]'); // for data-change-this
document.querySelectorAll('.change-this.'); // for class change-this
编辑:关于这是如何工作的摘录
function changeHTMLTag()
{
var els = document.querySelectorAll('[data-replace-h3]');
for (var i = 0; i < els.length ; i++) {
els[i].outerHTML = '<h2>' + els[i].innerHTML + '</h2>';
}
}
&#13;
<h3 data-replace-h3>This is H3 Heading</h3>
<h3 data-replace-h3>This is H3 Heading</h3>
<h3 data-replace-h3>This is H3 Heading</h3>
<button type="button" onclick="changeHTMLTag()">I want to Replace H3 Tag by H2 Tag Using JavaScript</button>
&#13;