How to get DOM elements in a particular element?

2019-07-28 17:47发布

问题:

What I want to do

I want to get the center of the height of a specific element .main and get the DOM element that is there.


What I tried

I thought I could get a DOM element with elementFromPoint().

// Get the center of the height of .main
const rect = document.getElementsByClassName("main")[0].getBoundingClientRect();
const mainHCenter = rect.height / 2;
const mainWCenter = rect.width / 2;

// Get the element at the center of the height of .main
var centerElm = document.elementFromPoint(0, mainHCenter);

// Get the center of the height of .main
const main = document.querySelector(".main");
const centerY = main.offsetHeight / 2;
const centerX = main.offsetWidth / 2;

// Get the element at the center of the height of .main
const element = document.elementFromPoint(centerX, centerY);

But in either case, the retrieved DOM element was not as expected.
Apparently elementFromPoint() seems to get DOM elements based on viewport.


I wanted to use caretPositionFromPoint(), but with a small amount of browser support, this is not possible.

Q. Is there any better way to get DOM elements in a particular element?

回答1:

You are getting height and width centers but not adding the offsets for main from left and top of the document

I found element p.active by adjusting your demo to:

const rect = document.getElementsByClassName("main")[0].getBoundingClientRect();

const mainHCenter = rect.top + (rect.height / 2);
const mainWCenter = rect.left + (rect.width / 2);
                  // ^^^^^   add left and top offsets


var centerElm = document.elementFromPoint(mainWCenter, mainHCenter);
                                        // ^^^ don't use zero

console.log(centerElm);// returned p.active

DEMO