0

I am using a forEach method to add an event listener to each button, everything is working the first time, the function is calling the filterElements function as wanted BUT when i try to click a second time the code doesen't respond, could it be because of my HTML collection that I am transforming to an Array using Array.from or what could it be ?

function filterPhotograpsIndividualTages(dataJson) {
  
    const individualTags = Array.from(document.getElementsByClassName('individual-tags'));
    individualTags.forEach(btn => btn.addEventListener('click', () => {   //this is the forEach method
       
        /*onClick clear the old HTML of photographersDiv and call
         the function filterElements to execute his block code!*/
        document.getElementById('container').innerHTML = "";                                       
        filterElements(dataJson, btn);// function is invoked here
  })) 
};

// this function is being called inside of the filterPhotograpsIndividualTages function
function filterElements(dataJson, btn){ 

    dataJson.photographers.forEach(photographe => {

        if(photographe.tags.indexOf(btn.id) != -1) {

            const photographersDiv = document.getElementById('container');
            const div = document.createElement("div");
            div.innerHTML = `
                <div class="photographerContainer">
                    <a href="photographers.html?id=${photographe.id}">
                        <div class="portraitBox">
                            <img src="${photographe.portrait}" alt="photo">
                        </div>
                        <h1 class="name">${photographe.name}</h1>
                    </a>
                    <p class="city">${photographe.city}, ${photographe.country}</p>
                    <p class="tagline">${photographe.tagline}</p>
                    <p class="price">${photographe.price}€/jour</p>
                    <p class="tags">${photographe.tags.map(tag => `<button id=${tag} class="tag individual-tags">#${tag}</button>`).join(" ")}</p>  
                </div>
            `  
            photographersDiv.appendChild(div);
        }})
};

1 Answer 1

1

When you add event like this, it only binding to DOM you have selected with getElementsByClassName not with the one re-add after delete

Instead you should bind whole document and check event's target

document.addEventListener('click', function(event) {
    if (event.target.classList.contains('your_class')) {
        Function();
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.