Home > Software design >  How to use getElementsByClassName on dynamic html
How to use getElementsByClassName on dynamic html

Time:02-20

What Im 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

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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

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