当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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>

网友答案:
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)

网友答案:
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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: