profiles.forEach(profile => {profilesGrid.insertAdjacentHTML('beforeend', profileCard);} - добавляю элементы таким образом, другим скриптом хочу получить var btn = document.getElementsByClassName('myBtn'), который внутри карты профиля, но оно не находит идшник(из за того что страница еще не прогрузила, т.к оно в js). defer пробовал, не помогло. Как можно решить проблему
Pashok576, почему не парсишь его через селекторы или почему не пропишешь чтобы он его получал из объектов, не особо понятно че ты хочешь
Shadowraze, <script> // Fetch profile data from the Flask server fetch('/api/surveys') .then(response => response.json()) .then(profiles => { // Select the profiles grid element const profilesGrid = document.getElementById('profilesGrid'); // Clear the profiles grid profilesGrid.innerHTML = ''; //счетчик до 5, чтобы не было больше 5 карточек // Iterate over each profile and append HTML card profiles.forEach(profile => { const profileCard = ` <div class="col-lg-3 col-6 text-center mb-3 n profile-card" > <div class="card h-2" style="width: 16rem; height: 25rem;"> <img src="${profile.photo}" class="card-img-top card-bonus-icon myBtn" alt="${profile.photo}" style="height: 260px; width: 255px"> <div class="card-body"> <h5 class="card-title">${profile.nickname}</h5> <p class="card-text">${profile.description}</p> </div> <div class="card-footer"> <small class="text-muted">${profile.city}, ${new Date(profile.dob).toLocaleDateString()}</small> </div> </div> </div> `; profilesGrid.insertAdjacentHTML('beforeend', profileCard); }); }) .catch(error => console.error('Error fetching profiles:', error)); // JavaScript methods will be defined here // Implement sorting logic here // JavaScript methods will be defined here // Get the modal var modal = document.getElementById('myModal'); // Get the button that opens the modal var btn = document.getElementsByClassName('myBtn'); // Get the <span> element that closes the modal var span = document.getElementsByClassName('close')[0]; // Get the button that sends the like var sendLikeBtn = document.getElementById('sendLike'); // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = 'block'; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = 'none'; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = 'none'; } } // When the user clicks the send like button, send the like to the backend sendLikeBtn.onclick = function() { const comment = document.getElementById('likeComment').value; fetch('/api/send_like', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ comment: comment }) }) .then(response => { if (response.ok) { modal.style.display = 'none'; // Handle success - maybe display a message to the user } else { // Handle error - maybe display an error message to the user } }); } </script> HTML <script> // Fetch profile data from the Flask server fetch('/api/surveys') .then(response => response.json()) .then(profiles => { // Select the profiles grid element const profilesGrid = document.getElementById('profilesGrid'); // Clear the profiles grid profilesGrid.innerHTML = ''; //счетчик до 5, чтобы не было больше 5 карточек // Iterate over each profile and append HTML card profiles.forEach(profile => { const profileCard = ` <div class="col-lg-3 col-6 text-center mb-3 n profile-card" > <div class="card h-2" style="width: 16rem; height: 25rem;"> <img src="${profile.photo}" class="card-img-top card-bonus-icon myBtn" alt="${profile.photo}" style="height: 260px; width: 255px"> <div class="card-body"> <h5 class="card-title">${profile.nickname}</h5> <p class="card-text">${profile.description}</p> </div> <div class="card-footer"> <small class="text-muted">${profile.city}, ${new Date(profile.dob).toLocaleDateString()}</small> </div> </div> </div> `; profilesGrid.insertAdjacentHTML('beforeend', profileCard); }); }) .catch(error => console.error('Error fetching profiles:', error)); // JavaScript methods will be defined here // Implement sorting logic here // JavaScript methods will be defined here // Get the modal var modal = document.getElementById('myModal'); // Get the button that opens the modal var btn = document.getElementsByClassName('myBtn'); // Get the <span> element that closes the modal var span = document.getElementsByClassName('close')[0]; // Get the button that sends the like var sendLikeBtn = document.getElementById('sendLike'); // When the user clicks on the button, open the modal btn.onclick = function() { modal.style.display = 'block'; } // When the user clicks on <span> (x), close the modal span.onclick = function() { modal.style.display = 'none'; } // When the user clicks anywhere outside of the modal, close it window.onclick = function(event) { if (event.target == modal) { modal.style.display = 'none'; } } // When the user clicks the send like button, send the like to the backend sendLikeBtn.onclick = function() { const comment = document.getElementById('likeComment').value; fetch('/api/send_like', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ comment: comment }) }) .then(response => { if (response.ok) { modal.style.display = 'none'; // Handle success - maybe display a message to the user } else { // Handle error - maybe display an error message to the user } }); } </script>
Pashok576, ну во-первых, чистый js не всегда лучше, я бы на твоем месте использовал jquery. Во-вторых, событие onclick срабатывает только на элементы, которые существовали при загрузке dom. В jq есть отдельный хандлер для событий on() , либо используй addEventListener . Ну еще ты вызываешь var btn = document.getElementsByClassName('myBtn') до того, как у тебя все карточки создались.