繁体   English   中英

使用Pure JS更改HTML标签名称

[英]change HTML tag name using Pure JS

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

我想使用纯JavaScript来更改标签名称,
有人可以帮忙吗?

通过一些时髦的dom操作,您可以轻松做到这一点。

您只需要制作一个新元素,将其移至所有元素上,以便保留onclick处理程序等,然后替换原始内容。

 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"> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM