Get child element by coordinates

javascript, jquery

Solution

You could use `document.elementsFromPoint` instead.

It returns an array.

`const elementsAtPoint = document.elementsFromPoint(x, y)`

`const numberOfElementsAtPoint = elementsAtPoint.length`

The most deeply nested elements are first in the array, while the outermost elements are last. You could find your parent element by its id, and return the element before it in the array.

Something like this verbose step-by-step:

const elementsAtPoint = document.elementsFromPoint(x, y);

const elementIds = elementsAtPoint.map(element => element.id);

const parentIndex = elementIds.indexOf("parent");

const childIndex = parentIndex - 1;

const childElement = elementsAtPoint[childIndex];

I did some testing in console, I think this should work. You'd have to handle cases where you don't find your elements too.

I would probably rewrite it to a function along the lines of:

function getChildAtPoint(parentId, x, y){
  const elementsAtPoint = document.elementsFromPoint(x, y);

  const elementIds = elementsAtPoint.map(element => element.id);

  const parentIndex = elementIds.indexOf(parentId);

  // If we can't find element with parentId, or it is the first 
  // in the array we found nothing.
  if( parentIndex < 1 ){ return; };

  const childIndex = parentIndex - 1;

  const childElement = elementsAtPoint[childIndex];

  return childElement;
}

Problem

Consider the following markup ``` <div id = "parent"> <a id = "child1" href = "#">1</a> <a id = "child2" href = "#">2</a> <a id = "child3" href = "#">3</a> <a id = "child4" href = "#">4</a> </div> ``` I need to get a child inside parent by its position(X an d Y coordinate). When I use `var element = document.elementFromPoint(x, y);` it returns parent element. Is there a way to get child element?

Original source