Home > Mobile >  Javascript click event doesn't work properly I can't give class
Javascript click event doesn't work properly I can't give class

Time:11-05

function getCountryByDiv(selectedCountry) {
            x = document.getElementById("neighbors").children;
            console.log(x);
            for (let i of x){
                console.log(i);
                if(i.classList.contains("clicked")){
                    i.classList.remove("clicked");
                }
                else{
                    selectedCountry.classList.add("clicked");
                    console.log("evet");
                }
            }
            htag = document.querySelector(".clicked .card-title");
            console.log(htag);
            getCountry(htag.innerText);
        }

        function renderNeighbors(data) {
            console.log(data);
            let html = "";

            for (let country of data) {
                html  = `
                <div onclick="getCountryByDiv(this)" >
                    <div >
                        <img src="${country.flags.png}" >
                        <div >
                            <h6 >${country.name.common}</h6>
                        </div>
                    </div>
                </div>
            `;

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

Click event doesn't work properly and I don't know why. When I click to the last child it can't find innerText. But there is innerText. I can't see any problem but it still doesn't work. I can't give class to the last child (.clicked).

Error](https://i.stack.imgur.com/RFfqy.png)

But it has innerText](https://i.stack.imgur.com/DSCvX.png)

If you want I can send the whole code.

design](https://i.stack.imgur.com/62iVm.png)

I'm trying to give class to the last child and send the innerText of h6 to the function.

(English is not my native tounge so if I wrote anything wrong sorry about that.)

CodePudding user response:

You have to add the "clicked" on the clicked div outside of the loop. You already pass the clicked elem as a parameter, so you can set it directly:

function getCountryByDiv(selectedCountry) {
        x = document.getElementById("neighbors").children;
        console.log(x);
        for (let i of x){
            console.log(i);
            if(i.classList.contains("clicked")){
                i.classList.remove("clicked");
            }
        }
        // moved here
        selectedCountry.classList.add("clicked");
        
        htag = document.querySelector(".clicked .card-title");
        console.log(htag);
        getCountry(htag.innerText);
    }

In the original code it failed on the last element because there was no following element which resetted the class "clicked" in the else-condition.

  • Related