Can I change a paragraph tag to a title tag using JavaScript?

I am trying to change a paragraph element by its id in JavaScript to h1 .

My html

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

My javascript

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

Required Result:

 <body> <h1 id="damn"> Hello </h1> </body> 
+4
source share
2 answers
 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'); 

(violin)

+2
source
 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 with me .

+1
source

Source: https://habr.com/ru/post/1489632/


All Articles