Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to change a nodes name?

For example I have this HTML:

<body>
    <div>Text</div>
</body>

And I would like to change the div to something else like p.

This is what I have tried but doesn't works:

var div = document.getElementsByTagName("div")[0]; // Get Element
    div.nodeName = "p"; // Change It's Node Name to P

Please no libraries, and I don't really want to replace the actual div with a new p :)

like image 322
Adam Halasz Avatar asked Oct 27 '25 09:10

Adam Halasz


1 Answers

You cannot just change an element. You have to create a new one. E.g.:

var div = document.getElementsByTagName("div")[0];
var p = document.createElement('p');
p.innerHTML = div.innerHTML;
div.parentNode.replaceChild(p, div);

But this could lead to invalid markup, if the original element contains nodes that cannot be descendants of the new node.

Reference: document.createElement, Node.replaceChild


Note: A better version (because it doesn't depend on serializing DOM to text and back and preserves attributes), can be found at https://stackoverflow.com/a/8584158/218196 .

like image 68
Felix Kling Avatar answered Oct 29 '25 22:10

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!