Where is the document.getElementById method defined?

Note. This is for educational purposes only.

console.log(this); document.getElementById = function(){ alert('testing'); } document.getElementById('someID'); 

I have javascript code written above. When I load the page, it shows a warning window that says "Testing."

So, I assume that getElementById is a method of the document object, and I rewrote it to alert('testing') , so it shows me a warning window when the page loads.

If this part is correct, shouldn't I see getElementById when I expand the document object below? Am I looking for him in the wrong place or something like that?

enter image description here

+5
source share
2 answers

Your method is there. Only chrome decided not to show you.

WvqIk37.png

If you must do this, this is another question.

+6
source

What you are doing is overriding the document.getElementById() function with your own implementation. The logger just does not display all the properties of the document element. Assigning it to a new object does the trick:

 document.getElementById = function() { console.log('test'); } var doc = Object.assign({}, document); console.log(doc); console.log(doc.getElementById); 
 .as-console-wrapper { max-height: 100% !important; } 

Important Note

I highly recommend that you do not replace the getElementById() functionality with your own, as this can lead to any troubles. It would be much better to extend the document object to a user-defined function.

+4
source

Source: https://habr.com/ru/post/1272209/


All Articles