Is it possible to change paragraph tag to header tag by using JavaScript?

♀尐吖头ヾ 提交于 2021-02-19 02:40:53

问题


I'm trying to change a paragraph element by its ID in JavaScript to a h1.

My HTML

<body>
   <p id="damn"> Hello </p>
</body>

My JavaScript

<script>
    document.getElementByID("damn").<required missing code to change to h1>
</script>

The required result is

<body>
   <h1 id="damn"> Hello </h1>
</body>

回答1:


function changeTagName(el, newTagName) {
    var n = document.createElement(newTagName);
    var attr = el.attributes;
    for (var i = 0, len = attr.length; i < len; ++i) {
        n.setAttribute(attr[i].name, attr[i].value);
    }
    n.innerHTML = el.innerHTML;
    el.parentNode.replaceChild(n, el);
}

changeTagName(document.getElementById('damn'), 'h1');

(fiddle)




回答2:


var elem=document.getElementById("damn");
var parent=elem.parentNode;
var newElement=document.createElement("h1");
newElement.textContent=elem.textContent;
newElement.id=elem.id;
parent.replaceChild(newElement, elem);

That should do the trick. Play around with me.



来源:https://stackoverflow.com/questions/17463930/is-it-possible-to-change-paragraph-tag-to-header-tag-by-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!