0

Essentially I've got a button on the website where you can add < span > elements that have a class called; class="text_box".

The idea is, whenever you click any of these elements with the class "text_box", it console.logs a message.

I've got a function that handles this.

Everytime a new element is created Dynamically (Via DOM.createElement) It reruns this function so that the querySelectorAll updates, therefore this newly created element is now part of that array. (the wysiTextElms array of elements with class="text_box")

function textElmEventListener(){
    //Get's all Text box elements:
    wysiTextElms = document.querySelectorAll(".text_box")

    //Creates event listener for all of them.
    for (const t_e of wysiTextElms) {
        t_e.addEventListener("click", function(e) {
        console.log(t_e);
    });
    }
};

The issue is..

Let's say I got 3 elements with the class "text_box"

<span contenteditable="" class="text_box">span1</span>
<span contenteditable="" class="text_box">span2</span>
<span contenteditable="" class="text_box">span3</span>

When I click on span1, I'll get:

<span contenteditable="" class="text_box">span1</span>
<span contenteditable="" class="text_box">span1</span>
<span contenteditable="" class="text_box">span1</span>

It repeats the command 3 times,

For span2, It will repeat twice

and only for span3 will it just execute the console.log once..

I've tried to use break so that once it executes once it breaks out the loop, but it gives me the Illegal break statement.

Any insight is appreciated!

jasonmzx
  • 113
  • 8
  • 2
    Your existing elements already have the event listener, so adding it to them again will make them have two event listeners, then three, then... – Nick May 02 '21 at 00:08
  • 1
    Why don't you just run a global click event listener and check for the attribute name, id or class? Would require less listeners and run smoother. Less confusing too! – blanknamefornow May 02 '21 at 00:10
  • 1
    Also what Nick said, but to detail it re-executing your textElmEventListener will add this listener and duplicate it. – blanknamefornow May 02 '21 at 00:11
  • 1
    The `document.createElement` that you are using returns an element that you can call `.addEventListener()` on. Just add your event listener to that one element when you create it. – Ivar May 02 '21 at 00:11
  • Ahhhh Ok I see now, I didn't know that was a thing Thank you guys I'll try this out right now! – jasonmzx May 02 '21 at 00:12

0 Answers0