Get DOM text node from point?

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?



Here is an implementation that works in all current browsers:

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();
            var rects = r.getClientRects();
            for ( var j = 0, rect; rect = rects[j++];) {
                if (x > rect.left && x < rect.right && y > && y < rect.bottom) {
                    return n;
    return el;

For Firefox, you should use document.caretPositionFromPoint

Here's a greap demo:

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


You can use element.nodeName to see if it's a text node, and then element.nodeValue for its value.


Considering this document (fiddle):

    some text here 
    <p id="para1">lalala</p> 
    bla bla

And this code:

$(document).on('click', function(evt) {
    var elem = document.elementFromPoint(evt.clientX, evt.clientY);

When you click anywhere inside the <p> tag, the tag element itself is logged. However, when the surrounding text is clicked, the <body> is returned because text fragments are not considered elements.


It's not possible to accomplish what you want with elementFromPoint() and because text fragments don't receive click events, I don't think it's possible at all.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.