4

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?

4
  • could you please show us how X and Y values getting use for child element in html, so that we can relate the problem easily? Nov 28, 2014 at 11:56
  • 1
    The shown HTML is invalid
    – Andreas
    Nov 28, 2014 at 11:59
  • With fixed markup it works - jsfiddle.net/ha0gepbn
    – Andreas
    Nov 28, 2014 at 12:01
  • sure, markup was wrong.thanks Nov 28, 2014 at 12:05

1 Answer 1

5

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.