Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

js asynchronous problem just work first neighbor

I want click neighbor and change the main country. I click first card ok no problem. but other cards not working. This is my code:

function renderNeighbors(data) {
    let html = "";
    for (let country of data) {
        html += `
                <div class="col-2 mt-2">
                    <div class="card click-change">
                        <img src="${country.flags.png}" class="card-img-top">
                        <div class="card-body">
                            <h6 class="card-title neighborName">${country.name.common}</h6>    
                        </div>
                    </div>
                </div>
            `;
    }

    document.querySelector("#neighbors").innerHTML = html;

    document.querySelector(".click-change").addEventListener("click", () => {
        let neighborName = document.querySelector(".neighborName").innerHTML;

        getCountry(neighborName);
    })
}

in photos I point red circle in my browser. that’s only working card.
enter image description here

I want to click neighbors and change main country. but only work for first neighbor

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

here is my all html code https://pastebin.com/Sb9XWZhy

>Solution :

here, the problem you are setting your event only for the first chosen element that matches your locator .

querySelector return only the first element that matches.

you should add the event for all of your nodes that match the locator.

It’s supposed that querySelectorAll returns an array that you can loop over it like that.


for (let element of document.querySelectorAll(".click-change")){
    element.addEventListener("click", () => {
            let neighborName = 
 element.children[1].children[0].innerHTML;//here I'm accessing the neighbourName from the element itself, I'm not sure about the indices but you can handle them yourself

            getCountry(neighborName);
        })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading