How do I write a JS function to remove the span on click and just retain the inner text ?
<span class="test" onclick="removespan(this);">Data in red</span>
removespan = function(e){
alert(e.innerText);
}
CSS : span.test{color:red;}
onclick I would like to remove the span and just retain the inner text . Infact I would like to have a onmodify event ...that removes the span . The purpose is to remove a spellchecker span class in WYSIWYG editor .
How do I write a JS function to remove the span on click and just retain the inner text ?
<span class="test" onclick="removespan(this);">Data in red</span>
removespan = function(e){
alert(e.innerText);
}
CSS : span.test{color:red;}
onclick I would like to remove the span and just retain the inner text . Infact I would like to have a onmodify event ...that removes the span . The purpose is to remove a spellchecker span class in WYSIWYG editor .
Share Improve this question edited Jul 24, 2012 at 13:54 Mark Schultheiss 34.2k12 gold badges72 silver badges113 bronze badges asked Feb 28, 2012 at 5:44 NishantNishant 22k20 gold badges78 silver badges106 bronze badges 1- Is this span is the only element in its parent node ? – Diode Commented Feb 28, 2012 at 5:49
3 Answers
Reset to default 4If the span is the only child element inside its parent node
<div>
<span class="test" onclick="removespan(this);">Data in red</span>
</div>
removespan = function(span) {
span.parentNode.innerHTML = span.innerHTML;
}
Otherwise use this function
removespan = function(span) {
span.parentNode.replaceChild(document.createTextNode(span.innerHTML), span);
}
In case anyone is interested in an "expanded" version of Diode's second option:
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);
}
<span id="test"></span>
y=doc.getElementsById("test");
y.getParent().removeChild(y);