Skip to content Skip to sidebar Skip to footer

What Is The Implementation Of Getelementbyid()?

Can somebody please explain to me the internal implementation of HTML getElementById() method ? Is it traversing whole DOM tree to find the specified element or is it intelligent e

Solution 1:

The implementation is entirely (er) implementation-dependent. Some browsers may use a hashmap or similar, or they may not (because although id is required to be unique, there are lots of poorly-authored pages out there that provide invalid markup with duplicated ids). Internet Explorer 6 and 7 don't even limit getElementById to id values, they conflate namespaces terribly, although Microsoft has clearly seen the light and both IE8 and IE9 improve that.

For browsers that are implemented open source, you can find out, of course. Here's a link to the WebKit source, and here's one to Mozilla's(that line number may vary a bit, if you don't land right on it, just search for GetElementById and GetElementByIdInternal). Both of those come from this related answer here on StackOverflow. (In fact, looking at that question, I think this one may be a duplicate, although as Matthew points out in a comment below, things are moving fast enough that it might justify an update...)

Solution 2:

It depends on the browser, but most probably use a hash map from id->element. It's true that there are many invalid pages that have duplicate ids. However, the browser will still only return one element, not a collection.

I don't know what you mean by "near by elements" since the method only exists on document.

If you're interested, you can find the implementation for free software browsers such as Firefox and Chrome.

Solution 3:

That depends. The method is implemented by each web browser vendor, so the details may be different from one to another and possibly from one version of a browser to another.

I'd suggest taking a look at the source code for a browser such as Mozilla Firefox and see if you can find the implementation.

Post a Comment for "What Is The Implementation Of Getelementbyid()?"