I want to delete the previous and next HTML element after using the mouse highlighting the selected text by javascript, but I only know how to get the selected/highlighted text, can anyone help me? Thank you.
function text() {
if (window.getSelection)
return window.getSelection();
if (document.getSelection)
return document.getSelection();
if (document.selection)
return document.selection.createRange().text;
return "";
}
function delete_Tag () {
var txt = text();
// txt already have the selected text
// I don't know how to do in here !!!
// I use the use the find the parentNode, but don't know how to delete the </span>
}
<input type='button' value='Delete Tag' onclick='delete_Tag ()' />
<p id='text'>
<span class="B">I am </span>
<span class="B">working in </span>
<span class="C">ABC company.</span>
</p>
e.g. I use the mouse to highlight the 'working in ' OR 'orkin' (the selected must be within the ) and click the button, it will show
Expected Result:
<p id='text'>
<span class="B">I am </span>
working in
<span class="C">ABC company.</span>
</p>
You can use something like the following:
var span = document.getElementsByClassName("B").item(0);
var parent = span.parentNode;
var sibling = span.nextSibling;
var textNode = document.createTextNode(span.innerHTML);
parent.removeChild(span);
parent.insertBefore(textNode, sibling);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With