1

In jQuery there is the script

$(document).on('click', '#popup-pers .mfp-close', function(e){});,

is used if .mfp-close is virtual element that appear not by load the page, but by event, instead

$(#popup-pers .mfp-close).click();

I need the same analogue for JS. I use

pers_hide = querySelector('#popup-pers .mfp-close');

but browser sees just #popup-pers , not '#popup-pers .mfp-close'

user43436
  • 31
  • 3

1 Answers1

0

For dynamically created elements on whom you want to assign a click event before they are inserted in the DOM - Assign the event to the parent delegator, and than query the Event Event.target.closest(selector) matches the desired dynamic child selector.

Here are two possible solutions/suggestions:

Create your own on() helper:

// DOM utility functions:
const el = (sel, parent) => (parent ||document).querySelector(sel);
const elNew = (tag, props) => Object.assign(document.createElement(tag), props);

// On handler:
const on = (eventName, delegator, target, cbFn, opts) =>
  el(delegator).addEventListener(eventName, evt =>
    evt.target.closest(target) && cbFn(evt), opts);

// Task:

// 1. Assign events beforehand:
on("click", "#popup-pers", ".mfp-close", (evt) => {
  console.log(evt.target.textContent);
});

// 2. Insert element afterwards:
el("#popup-pers").append(elNew("button", {
  type: "button",
  className: "mfp-close",
  textContent: "CLICK"
}));
#popup-pers {
  background: gold;
  padding: 10px;
}
<div id="popup-pers"></div>

Assign the event when creating your elements

Otherwise assign the desired event handler function on Element creation, by using the onclick method (which is the only valid way that property should ever be used, and that's when creating new in-memory elements):

// DOM utility functions:
const el = (sel, parent) => (parent ||document).querySelector(sel);
const elNew = (tag, props) => Object.assign(document.createElement(tag), props);

// Task:
// Insert element with click function assigned:

el("#popup-pers").append(elNew("button", {
  type: "button",
  className: "mfp-close",
  textContent: "CLICK",
  onclick() {
    console.log(this.textContent);
  }
}));
#popup-pers {
  background: gold;
  padding: 10px;
}
<div id="popup-pers"></div>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313