The children of the querySelectorAll delegate event target are also bound to the event

html

    <ul class="parent">
        <li class="nodeChild1">
        1
            <a href="javascript:void(0)"></a>
        </li>
        <li class="nodeChild2">2</li>
        <li class="nodeChild3">3</li>
        <li class="nodeChild4">4</li>
    </ul>

script

    var show = function (e) {
        var pDiv = e.target,
            cDiv = document.createElement("div");
        pDiv.appendChild(cDiv);
        cDiv.innerText = "hhhhhhhhh";
    }
    var unboundForEach = Array.prototype.forEach,
        forEach = Function.prototype.call.bind(unboundForEach);
    forEach(document.querySelectorAll(".parent li"), function (el) {
        el.addEventListener("click", function (e) {
            show.call(this,e)
            console.log(e)
        });

    });

when I click on the a tag in className"nodeChild1", the a tag also executes the show () function and creates a div, in the a tag. Is this the principle of bubbling? When you click the a tab, how do you get the pointer of the show () method to point to his parent li to create a div in it?

Sep.29,2021

to determine that target's nodeName, is not li, find his parent


make two changes to your code to see if it's what you want

var show = function () {

  var pDiv = this,  //
    cDiv = document.createElement('div');
  pDiv.appendChild(cDiv);
  cDiv.innerText = 'hhhhhhhhh';
}
var unboundForEach = Array.prototype.forEach,
  forEach = Function.prototype.call.bind(unboundForEach);
forEach(document.querySelectorAll('.parent li'), function (el) {
  el.addEventListener('click', function (e) {
    show.call(el, e)  //
    console.log(e)
  });

});
Menu