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>
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);
You can use Jquery hide
method.
It would seem that your having trouble deleting the elements, it may be more efficient to hide the selected elements rather than using jQuery.
You need do some extra stuff. You need catch document.body.onmousedown and document.body.onmouseup. If targets of this events are the same node then you have to save this node for further use.
I have created working example for you
精彩评论