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

我想使用純javascript來更改標記名稱,
任何人都可以幫忙嗎?使用Pure JS更改HTML標記名稱

+1

你不能直接這樣做,你有一個新的元素添加到DOM和移動你的內容到它。 – Brian

+0

看看這個答案http://stackoverflow.com/a/3435943/2120289 –

回答

0

隨着一些時髦的操縱你可以輕鬆地做到這一點。

您只需製作一個新元素,移動所有元素,以便保持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">

+0

不錯的工作,感謝您的幫助! –

+0

如果您認爲這是正確的答案,請打黑色箭頭下的複選標記 – Tschallacka