не работают скрипты внутри foreach при GET запросе

Есть рабочий пример скрипта на javascript, который подгружает контент при скролле. Все работает, но внутри foreach модальные окна не открываются и вообще скрипты не работают. Буду очень признателен за помощь.

<script>
    const citiesContainer = document.getElementById('cities');
    const btnLoad = document.getElementById('load');
    const loader = document.querySelector('.loader');
    let page = 1;
    let lock = false;

    async function getCities() {
        const res = await fetch(`index.php?page=${page}`);
        return res.text();
    }

    // getCities();
    async function showCities() {
        const cities = await getCities();
        if (cities) {
            citiesContainer.insertAdjacentHTML('beforeend', cities);
            lock = false;
        } else {
            btnLoad.classList.add('d-none');
            lock = true;
        }
    }

    loader.classList.add('show');
    setTimeout(() => {
        showCities();
        loader.classList.remove('show');
    }, 1000);

    btnLoad.addEventListener('click', () => {
        loader.classList.add('show');
        setTimeout(() => {
            page++;
            showCities();
            loader.classList.remove('show');
        }, 1000);
    });

    window.addEventListener('scroll2', () => {
        const {scrollTop, scrollHeight, clientHeight} = document.documentElement;
        // console.log(scrollTop, scrollHeight, clientHeight);
        if (scrollTop + clientHeight >= scrollHeight) {
            if (false === lock) {
                lock = true;
                loader.classList.add('show');
                setTimeout(() => {
                    page++;
                    showCities();
                    loader.classList.remove('show');
                }, 1000);
            }
        }
    });


 // МОДАЛЬНОЕ ОКНО //

document.addEventListener('DOMContentLoaded', () => {
    const mOpen = document.querySelectorAll('[data-modal]');
    if (mOpen.length == 0) return;  // если нет элементов управления всплывающими окнами, прекращаем работу скрипта

    const overlay = document.querySelector('.modal__overlay'),
        modals = document.querySelectorAll('.modal__body'),
        mClose = document.querySelectorAll('[data-close]');

    for (let el of mOpen) {
        el.addEventListener('click', modalShow);    // регистрируются обработчик события открытия модального окна
    }
    for (let el of mClose) {
        el.addEventListener('click', modalClose);   // регистрируются обработчик события нажатия на крестик
    }

    document.addEventListener('keydown', modalClose);   // регистрируются обработчик события нажатия на клавишу

    function modalShow(modal) {
        let modalId = this.dataset.modal;
        document.getElementById(modalId).classList.add('open');
        overlay.classList.add('open');
    }

    function modalClose(event) {
        if ( event.type != 'keydown' || event.keyCode === 27 ) {
            for (let modal of modals) {
                modal.classList.remove('open');
                overlay.classList.remove('open');
            }
        }
    }
    
})

 // -- //

</script>
<style>
.loader {display: none;}
.loader img {width: 100px;}
.show {display: block;}

.modal__body {
    position: fixed; top: 0; left: 50%; margin: 8px 0; max-height: 95%; width: 95%; max-width: 500px;
    opacity: 0; visibility: hidden; z-index: 5; background: #F4F5F5;
    -webkit-transition: 0.3s all; -moz-transition: 0.3s all; -o-transition: 0.3s all; -ms-transition: 0.3s all; transition: 0.3s all;
    -webkit-transform: translate(-50%, -100%); -moz-transform: translate(-50%, -100%); -ms-transform: translate(-50%, -100%); transform: translate(-50%, -100%);
}

</style>
<?php
function get_start(int $page, int $per_page): int {
    return ($page - 1) * $per_page;
}

function get_cities(int $start, int $per_page): array {
    global $db;
    $stmt = $db->prepare("SELECT * FROM city LIMIT $start, $per_page");
    $stmt->execute();
    return $stmt->fetchAll();
}



if (isset($_GET['page'])) {
    $page = (int)$_GET['page'];
    $per_page = 200;
    $start = get_start($page, $per_page);
    $cities = get_cities($start, $per_page);
    $html = '';
    if ($cities) {
        foreach ($cities as $city) {
            $html .= "
            <li>
                {$city['name']}: {$city['population']}   
                <a href='javascript:void(0)' data-modal='com-delete_{$city['id']}'>Удалить</a>
            </li> 

                <!--  Модальное окно -->
                <div class='modal__body' id='com-delete_{$city['id']}'>
                    <div class='modal__content'>
                        <a href='/comments/control/action/delete/id/565' class='button'>Удалить</a>
                        <a href='javascript:void(0)' class='button' data-close=''>Отмена</a>
                    </div>
                </div>";
        }
    }
    echo $html;
    die;
}
?>


<ul id="cities"></ul>

<div class="loader">
    <img src="ripple.svg" alt="">
</div>
<button class="btn btn-primary" id="load">Load more</button>

<footer style="background-color: #000; height: 200px; padding: 0;"></footer>


Ответы (1 шт):

Автор решения: Hunter o_0

Разобрался, терь работает. Все время не те родительские контейнера применял))

<?
if (isset($_GET['page'])) {
    $page = (int)$_GET['page'];
    $per_page = 200;
    $start = get_start($page, $per_page);
    $cities = get_cities($start, $per_page);
    $html = '';
    if ($cities) {
        foreach ($cities as $city) {
            $html .= "
            <li>
              <button class='alert-button'>Button 1</button>
              <button class='alert-button'>Button 2</button>
            </li> 

              ";
        }
    }
    echo $html;
    die;
}

?>

<script>
  const container = document.querySelector('#cities');

  // Click handler for entire DIV container
  container.addEventListener('click', function (e) {
    // But only alert for elements that have an alert-button class
    if (e.target.classList.contains('alert-button')) {
      alert(e.target.innerHTML);
    }
  });

  const newBtn = document.createElement('button');
  newBtn.classList.add('alert-button');
  newBtn.innerHTML = 'Button 3';
  container.append(newBtn);
</script>

→ Ссылка