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?