我想使用JavaScript替换H2标签的H2标签

时间:2017-02-19 01:34:01

标签: javascript

我希望使用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>

1 个答案:

答案 0 :(得分:1)

只需更改H3标签的outerHTML,如下所示:

&#13;
&#13;
    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;
&#13;
&#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

编辑:关于这是如何工作的摘录

&#13;
&#13;
    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;
&#13;
&#13;