This example code used elementFromPoint
to illustrate the kind of task I’d like to perform but the question is rather than being confined to viewport coordinates and that which is visible, is there a way to get the element at a particular offest within scrl_can
that is not currently displayed in the container, apart from iterating through all the child elements and testing for one for which offset is between (offsetTop, offsetTop + offsetHeight)
? Is there a native method that will return similar to elementFromPoint
but relative to another element?
For example, suppose the height or every tr
is not guaranteed to be the same, and I want to know which tr
is at an offset of 400px when the scrl_can scrollTop is zero such that that tr
is not visible.
Thank you.
var
table = document.querySelector("TABLE"),
scrl_can = table.parentNode,
input = scrl_can.previousElementSibling,
button = input.previousElementSibling,
tbody = document.createElement("TBODY"),
tr,
td =[],
gBCR = scrl_can.getBoundingClientRect()
;
for (let i = 0; i < 26; i++ ) {
tr = document.createElement("TR")
tr.append(
td[0] = document.createElement("TD"),
td[1] = document.createElement("TD"),
td[2] = document.createElement("TD")
);
td[0].textContent = i + 1
td[1].textContent = String.fromCharCode(65+i);
td[2].textContent = String.fromCharCode(97+i);
tbody.append(tr);
}
table.append(tbody);
function GetTopRow() {
input.value = document.elementFromPoint(gBCR.left+3,gBCR.top+3).closest('tr').firstElementChild.textContent;
}
button.addEventListener( 'click', GetTopRow );
.scrl_can {
height: 150px;
width: fit-content;
overflow-y: scroll;
border: 1px solid black;
margin-top: 10px;
}
table {
padding: 0;
margin: 0;
border-collapse: collapse;
}
td {
padding: 5px 10px;
border: 1px solid black;
}
input {
width: 25px;
margin-left: 10px;
}
<button>Get Top Row</button><input type="text">
<div class="scrl_can">
<table></table>
</div>