JS event listener for a type of element?

前端 未结 5 1684
野趣味
野趣味 2021-01-22 18:47

Is there a way to add some kind of listener for a type of html element? For example if i wanna call a function when the user clicks any p element

5条回答
  •  醉梦人生
    2021-01-22 19:18

    Add the event listener to the window / document / document.body and check the type of the element and the types of its parents because if you have a inside a

    , clicking the span won't trigger the click in the paragraph.

    document.addEventListener("click", function (eventArgs) {
        var target = eventArgs.target;
        var elementToLookFor = "p";
        while (target !== null) {
            if (target.tagName.toLowerCase() === elementToLookFor) {
                // Do magic stuff with the paragraph
                console.log(target);
            }
            target = target.parentElement;
        }
    });
    

    This technique is called "event delegation."

    Edit: Note that you cannot early return from the loop above. If your have nested paragraphs, i.e.

    Hey,

    there!

    Having an early return will only call your event handler for the inner paragraph, whereas you said that you'd like the handler to be invoked on every paragraph which is why you need to traverse all the ancestors of the element.

提交回复
热议问题