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?
Document.getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
Introduction to JavaScript getElementById() methodThe document. getElementById() method returns an Element object that represents an HTML element with an id that matches a specified string. If the document has no element with the specified id, the document. getElementById() returns null .
The getElementById() method returns the elements that have given an ID which is passed to the function. This function is a widely used HTML DOM method in web designing to change the value of any particular element or get a particular element. If the passed ID to the function does not exist then it returns null.
Use the getElementById method to get an element by id if it exists, e.g. if (document. getElementById('my-id') !== null){} . The method returns the element whose id matches the provided string.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With