Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete the previous and next HTML element by javascript

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>
like image 241
John Avatar asked Dec 11 '25 11:12

John


1 Answers

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);
like image 81
Genady Sergeev Avatar answered Dec 14 '25 01:12

Genady Sergeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!