4

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>
rid
  • 61,078
  • 31
  • 152
  • 193
Canttouchit
  • 3,149
  • 6
  • 38
  • 51

2 Answers2

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)

rid
  • 61,078
  • 31
  • 152
  • 193
  • +1 this should be the accepted answer. It maintains all of the original elements attributes and by using innerHTML instead of textContent, it will retain any child elements (such as spans that might have style attached). – MrCode Jul 04 '13 at 07:41
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);

That should do the trick. Play around with me.

Thomas Junk
  • 5,588
  • 2
  • 30
  • 43