问题
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