javascript – Can i add an EventListener to a class i make in innerHTML-ThrowExceptions

Exception or error:

I am a new programmer to Javascript and i was wondering if i could add an addEventListener to a class i made in an innerHTML tag.

I would like to click it the class ‘favo_btn’ and give a uniek console.log to it.

   let str = '';
    str = document.createElement('div');
    if (result.results !== undefined) {
        for (let i = 0; i < result.results.length; i++) {
            console.log(result.results.length);
            str.innerHTML += `
            <div>
            <h2>${result.results[i].title}</h2>
            <img class="images" src="${result.results[i].thumbnail}">
            <p>${result.results[i].title}</p>
            <button class="favo_btn> <3 </button>
            </div>
            `
            ;
        };
    }
How to solve:

You can do the following:

const element = str.querySelector('selector');
element.addEventListener('click', ()=> {console.log(element.className)})

###

document.querySelector('.favo_btn').addEventListener('click', function(event){
console.log(event.target);
});

That will give your element.

Leave a Reply

Your email address will not be published. Required fields are marked *