0

I'm attempting to convert some jQuery code to vanilla js. I found this solution in a StackOverflow post, but now I can't find the original post.

My goal is to trigger a function after all of the dynamically created svg elements have been added to the DOM.

Here's the jQuery version:

jQuery("#svg1").on("jQuery_event", ".jQuery_event_class", function () {
  console.log("jQuery event");
});

jQuery("#svg1")
  .append('<g class="jQuery_event_class"></g>')
  .children()
  .last()
  .trigger("jQuery_event");

This vanilla js version doesn't work:

document.getElementById("svg1").addEventListener("js_event", function () {
  console.log("js event");
});

newElemParent = document.getElementById("svg1").getElementsByTagName("*");
newElemParent = document.getElementById("svg1").getElementsByTagName("*")[
  newElemParent.length - 1
];
newElem = newElemParent.appendChild(
  document.createElementNS("http://www.w3.org/2000/svg", "g")
);
newElem.dispatchEvent(new Event("js_event"));

Thanks!

adsy
  • 8,531
  • 2
  • 20
  • 31
fritz
  • 11
  • 2
  • The jQuery example adds a delegated listener for children of `#svg` which match `.jQuery_event_class`. To get that part working in vanilla js refer to https://stackoverflow.com/questions/23508221/vanilla-javascript-event-delegation – James Mar 31 '23 at 19:10
  • Please reopen. I see no reason why we shouldn't help fritz. The linked to posts are discussing a lot of stuff and the issue here is just some minor misunderstandings. – chrwahl Apr 02 '23 at 09:28

0 Answers0