Where is the method document.getElementById defined?

Viewed 262

Note: This is only for learning purpose..

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

document.getElementById('someID');

I have the above piece of javascript code written. When I load the page it shows an alert box saying 'Testing'.

So I am guessing getElementById is a method of the document object and I've overwritten it to alert('testing'), which is why its showing me the alert box when the page loads.

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

enter image description here

2 Answers

Your method is in there. It's just Chrome decided not to show you.

Whether you should do this, however, is another question of its own.

What you are doing is overriding the document.getElementById() function with your own implementation. The logger just doesn't show 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;
}

An important note

I would strongly recommend you do not replace the getElementById() functionality with your own, as it can lead to all sorts of trouble. It would be far better to extend the document object with a custom function, instead.

Related