change HTML tag name using Pure JS

梦想的初衷 提交于 2021-02-08 10:10:45

问题


<div id="demo"></div>
document.getElementsById("demo").onclick = function() {
    this.tagName = "p";
};
// and then the output should be:
<p id="demo"></p>

I want to use pure javascript to change the tag name,
could anyone help please?


回答1:


With some snazzy dom Manipulation you can do this easely.

You simply need to make a new element, move over all the elements so you keep onclick handlers and such, and then replace the original thing.

function addClickEventToSpan() {
  document.getElementById('whoa').addEventListener("click",function(){alert('WHOA WORLD! HELLO!');});
}
function transform(id){
     var that = document.getElementById(id);
  
     var p = document.createElement('p');
     p.setAttribute('id',that.getAttribute('id'));
     
     // move all elements in the other container.
     // remember to use firstchild so you take all the childrens with you and maintain order.
     // unles you like reversed order things.
     while(that.firstChild) {
       p.appendChild(that.firstChild);
     }
     that.parentNode.replaceChild(p,that);
     
}
p { background-color:green;color:white; }
div { background-color:blue;color:white; }
<div id="demo">Hello fantastical<span id="whoa" style="color:red">WORLD</span>
       <UL>
          <LI>something</LI>
  </UL>
</div>

<input type="button" onclick="addClickEventToSpan('demo')" value="bind event handler(click WORLD)">
<input type="button" onclick="transform('demo')" value="transform">


来源:https://stackoverflow.com/questions/29489160/change-html-tag-name-using-pure-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!