'How to use getElementsByClassName on dynamic html

What I'm trying to do is to get HTML tag by className on dynamic HTML that I fetched, but it returns undefined. It works if I try to getElementByClassName("main-page") because that class isn't dynamic

const HomePage = () => {
    const [pageData, setPageData] = useContext(PageContext)

    useEffect(() => {
        const allImages = document.getElementsByClassName("wp-block-column")
        console.log([...allImages])
    }, [])

    //render fronpage
    const renderMainPage = () => {
        //map the data and check for the site url (www.siteurl.com = front page)
        if (pageData) {
            return pageData.map(page => {
                if (window.location.origin + "/" === page.link) {
                    return <section dangerouslySetInnerHTML={{ __html: page.content.rendered }}></section>
                }
            })
        }
    }

    return (
        <h1 className="main-page"">{renderMainPage()}</h1>
    )
}

export default HomePage


Solution 1:[1]

From what I see the problem in pageData in context, probably your default value to context's pageData is false and renderMainPage() is not going further then first "if" statement

But its not preferred to use document selectors, use refs in React instead. Also from naming I see that you are trying to get images and not dom nodes, but with this logic you are going to get dom nodes. I'm sure there is better way/flow to access images you need than looking for them in nodes.

Solution 2:[2]

const elementsRef = useRef(data.map(() => createRef())); you can you dynamic create ref to access or create random iniNumber Array then assing to you elements when select them

Solution 3:[3]

You can use this function that useLayoutEffect, you can modify your code like this,

useLayoutEffect(()=> {
   document.getElementsByClassName("yourclassname")
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Max Onyshchenko
Solution 2 ATTILA
Solution 3 allen