是否可以使用JavaScript将段落标记更改为标题标记?

时间:2013-07-04 07:10:06

标签: javascript html dom

我正在尝试将段落元素的JavaScript中的ID更改为h1

我的HTML

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

我的JavaScript

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

所需的结果是

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

2 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:1)

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);

这应该可以解决问题。玩me