Javascript: How to change the host name?

For example, I have this HTML:

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

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

This is what I tried but does not work:

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

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

+4
source share
3 answers

You cannot just change an item. You must create a new one. For instance:.

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

But this can lead to invalid markup if the source element contains nodes that cannot be descendants of the new node.

Link: document.createElement , Node.replaceChild

+8
source

You can not.

As MDC docs say :

nodeName is a nodeName -only attribute.

You will need to create a new element and provide it with the correct content and attributes.

+1
source

You can not. By default, you are tagName, but it is read-only. Instead, you should create a new node of the desired type, and then transfer innerHTML (and any other properties, such as className or style) to the new node. Then insert the new node into the old parent of the node, then delete the old node (or use replaceChild).

In other words, a long road is the only road.

+1
source

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


All Articles