I’ve got a document that contains certain elements with unique ids
. This page contains what could be hundreds of different divs, each with their unique id. For example, consider the following:
<div id='root'>
<div id='my-1-id'>1</div>
<div id='my-2-id'>2</div>
<div id='my-3-id'>3</div>
<div id='my-4-id'>4</div>
<div id='my-5-id'>5</div>
// Even more divs
<div id='my-1000-id'>1000</div>
</div>
Within my React
component, I’ve implemented a LazyRendering
feature so that the document
gets loaded as the user scrolls down the page (which is pretty custom behavior).
However, right now, I’m looking to implement a feature that looks through certain parts of the page using document.getElementById
. But finding everything on the page isn’t working because the full document isn’t being rendered in one go. So if the user is on the top of the page and uses this functionality to look for something on the bottom of the page (i.e. the part that hasn’t been ‘lazy rendered’), then document.getElementById
will return null.
As a result of all this, I’m looking to implement a function that will simply loop over the document to search for this element. As an example:
const lookForElement = (id) => {
let element = document.getElementById(id)
while (!element) {
window.ScrollTo(0, 200) //NOT scrolling
element = document.getElementById(id)
}
return element
}
As you can see, if the element is not found, continue scrolling by 200 pixels in height until you find the element. However window.ScrollTo(0, 200)
isn’t working and the page is always fixated at the original height of the page. What am I doing wrong?