简体   繁体   中英

Prevent DOM elements from being added on every click

I have the following script which gets DOM elements with a given class, and adds them to an array. It then loops over the array and adds the values to option elements for a SelectControl component in WordPress Gutenberg. I'm able to get the elements into the array into the dropdown, but I'm receiving the following error: Uncaught TypeError: Cannot read property 'appendChild' of null in the console. It also doesn't show the selected option in the select component when selected and duplicates the array options in the dropdown every time an option from the dropdown is selected.

I suspect it may be an execution sequence issue, but not completely sure:

setTimeout(() => {
            let headers = [...document.querySelectorAll('.wp-block-heading')].map(item => item.innerText);
            const select = document.getElementById('selectheader');
            for (let i = 0; i < headers.length; i++) {
                let opt = headers[i];
                let el = document.createElement('option');
                el.textContent = opt;
                el.value = opt;
                select.appendChild(el);
            }
        }, 1000);


<SelectControl
    value={[headers]}
    id="selectheader"
    options={[headers]}
    onChange={setJumpLink}
/>

It actually needed:

if (select && select.innerHTML) {
    select.innerHTML = '';
}

before the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM