Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if selected text is inside a specific div

I have two divs as shown below:

<div id="div1">
<p>something</p>
<div><table><tr><td>Div1</td></tr></table></div>
</div>
<div id="div2">
<p>something else</p>
<div><table><tr><td>Div2</td></tr></table></div>
</div>
<button type="button">Check</button>

Now, I want to know when some text is selected and then the button pressed, if the selected text is under "div1" or not. How can I do that?

Edit: And the solution has to work in IE-7 and above.

like image 580
srinath Avatar asked Dec 01 '11 10:12

srinath


People also ask

How do I check if a div contains a text?

To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.

How to Highlight selected text in JavaScript?

getSelection() Method in JavaScript. The window. getSelection() method in JavaScript allows us to get the text highlighted or selected by the user on the screen. This method returns an object that contains information related to the text highlighted on the screen.


1 Answers

The elementContainsSelection() function below returns a boolean representing whether the specified element contains the whole of the user's selection and works in all major browsers, including IE 6.

Live demo: http://jsfiddle.net/eT8NQ/

Code:

function isOrContains(node, container) {
    while (node) {
        if (node === container) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
}

function elementContainsSelection(el) {
    var sel;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            for (var i = 0; i < sel.rangeCount; ++i) {
                if (!isOrContains(sel.getRangeAt(i).commonAncestorContainer, el)) {
                    return false;
                }
            }
            return true;
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        return isOrContains(sel.createRange().parentElement(), el);
    }
    return false;
}
like image 113
Tim Down Avatar answered Oct 08 '22 14:10

Tim Down