Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DOM text node from point?

Tags:

javascript

dom

Just like I can get an element from a point with document.elementFromPoint or document.getElementFromPoint, is it possible to somehow get a text node if the point is at a text node? I guess if at least I could get the text node's position and size I could then figure out which of them contains the point. But then DOM nodes don't have position properties. Is it possible to do this at all?

like image 756
Juan Avatar asked Nov 28 '12 03:11

Juan


People also ask

How do you find the text node of an element?

text(); This gets the contents of the selected element, and applies a filter function to it. The filter function returns only text nodes (i.e. those nodes with nodeType == Node. TEXT_NODE ).

What is text node in DOM?

HTML | DOM createTextNode() MethodThe createTextNode() method is used to create a TextNode which contains element node and a text node. It is used to provide text to an element. This method contains the text values as parameter which is of string type. Syntax: document.createTextNode( text )

What is nodeValue?

Definition and UsageThe nodeValue property sets or returns the value of a node. If the node is an element node, the nodeValue property will return null. Note: If you want to return the text of an element, remember that text is always inside a Text node, and you will have to return the Text node's node value (element.

What is elementFromPoint?

The elementsFromPoint() method of the Document interface returns an array of all elements at the specified coordinates (relative to the viewport). The elements are ordered from the topmost to the bottommost box of the viewport.


2 Answers

Here is an implementation that works in all current browsers: https://github.com/nuxodin/q1/blob/master/q1.dom.js

document.betaNodeFromPoint = function(x, y){
    var el = document.elementFromPoint(x, y);
    var nodes = el.childNodes;
    for ( var i = 0, n; n = nodes[i++];) {
        if (n.nodeType === 3) {
            var r = document.createRange();
            r.selectNode(n);
            var rects = r.getClientRects();
            for ( var j = 0, rect; rect = rects[j++];) {
                if (x > rect.left && x < rect.right && y > rect.top && y < rect.bottom) {
                    return n;
                }
            }
        }
    }
    return el;
};
like image 184
Tobias Buschor Avatar answered Oct 18 '22 21:10

Tobias Buschor


For Firefox, you should use document.caretPositionFromPoint

Here's a greap demo: https://developer.mozilla.org/en-US/docs/Web/API/document.caretPositionFromPoint

For Chrome and Edge, try document.caretRangeFromPoint(x,y)

like image 21
NamiW Avatar answered Oct 18 '22 20:10

NamiW