-1
document.getElementById('any').addEventListener() 

This code works well but when i searched in console I found that- addEventListener is a method of "document.body" and getElementById is a method of "document".

So how this code "document.getElementById('any').addEventListener()" actually works?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 3
    `addEventListener` is a method available to all objects that implement the [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) interface. DOM elements such as those returned by `document.getElementById` implement this interface, that is why you can call `addEventListener` on the return value of `document.getElementById`. Read: [EventTarget.addEventListener()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) – Yousaf Jun 30 '21 at 07:54

1 Answers1

0

@Yousaf has already given the basic and short answer.

But there is something called observer (a pattern), Which notifies automatically of any state changes.

The Observer will keep waiting for the state change, and then when it's changed the callback will be called notifying all the objects. The UML below will give you an idea of how it works.

enter image description here

Here is the detailed answer. original answer

Try to also read about CustomEvent

Hidayt Rahman
  • 2,490
  • 26
  • 32