2

I need to attach an event to a dynamically created element. With jQuery I can archive this by using the following code:

$("body").on("click", ".my-element", function() {});

And if I added a new .my-element, it automatically got the event attached.

I'm not creating the elements via document.createElement("div");, but I'm using pjax to reload just some parts of the page, so the main JavaScript file just loads one time, for that reason events need to be attached dynamically.

How can I achieve that with vanilla JavaScript?

KittMedia
  • 7,368
  • 13
  • 34
  • 38
legomolina
  • 1,043
  • 2
  • 13
  • 33

1 Answers1

4

A pure JavaScript version of your jQuery example

$("body").on("click", ".my-element", function() {});

would be:

document.body.addEventListener("click", function (e) {
    if (e.target &&
        e.target.classList.contains("my-element")) {
        // handle event here
    }
});

See example below.

const addTestElements = () => {
    var el = document.createElement("p"),
        node = document.createTextNode("Test element, class 'my-element'");

    el.classList.add("my-element");
    el.appendChild(node);
    document.body.appendChild(el);

    el = document.createElement("p");
    node = document.createTextNode("Test element, class 'test'");
    el.classList.add("test");
    el.appendChild(node);
    document.body.appendChild(el);
}

document.getElementById("add").addEventListener("click", addTestElements);

document.body.addEventListener("click", function (e) {
    if (e.target &&
        e.target.classList.contains("my-element")) {
        console.clear();
        console.log("An element with class 'my-element' was clicked.")
        e.target.style.fontWeight = e.target.style.fontWeight === "bold" ? "normal" : "bold";
    }
});
<button id="add">Add element</button>
Laurens Deprost
  • 1,653
  • 5
  • 16
  • Mmm, I'll give it a try! But, attach a body event listener is a good idea? Or is my jquery code doing it now? xD – legomolina Jan 06 '19 at 01:58
  • 1
    jQuery does the same thing under the hood: if the body is clicked, if check if it matches the selector (class "my-element" in this case) and executes the callback function when required. – Laurens Deprost Jan 06 '19 at 02:06