2012-02-28 5 views
2

クリックでスパンを削除して内部テキストを保持するJS関数を作成するにはどうすればよいですか?span onclickを削除するにはどうすればよいですか?

​<span class="test" onclick="removespan(this);">Data in red</span> 
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 
    ​removespan = function(e)​{ 
          alert(e.innerText); 
          }​ 
    CSS : ​span.test{color:red;} 

onclick私はスパンを削除し、内側のテキストを保持したいと思います。 Infact私はonmodifyイベントを持っています...それはスパンを削除します。 目的は、WYSIWYGエディターでスペルチェッカースパンクラスを削除することです。

+0

spanはその親ノード内の唯一の要素ですか? – Diode

答えて

3

スパンは誰でもダイオードのの「拡大」バージョンに興味がある場合はそれ以外の場合は

removespan = function(span) { 
    span.parentNode.replaceChild(document.createTextNode(span.innerHTML), span); 
} 
+0

+1の2番目のオプション! –

0
<span id="test"></span> 

y=doc.getElementsById("test"); 

y.getParent().removeChild(y); 
1

この機能を使用し、その親ノード

<div> 
    <span class="test" onclick="removespan(this);">Data in red</span> 
</div> 


removespan = function(span) { 
    span.parentNode.innerHTML = span.innerHTML; 
} 

内の唯一の子要素である場合2番目のオプション:

function removespan(span) { 
    // Get the text contents of the clicked span 
    var span_contents = span.innerHTML; 
    // Get the parent node of the clicked span 
    var span_parent = span.parentNode; 
    // Create a new text node in the DOM to hold the text contents 
    var text_node = document.createTextNode(span.innerHTML); 
    // Replace the clicked span node with your newly created text node 
    span_parent.replaceChild(text_node, span); 

    // Alternatively, do the above in one line... 
    // span.parentNode.replaceChild(document.createTextNode(span.innerHTML), span); 
} 
関連する問題