Saturday, 30 March 2019

Why isn't getElementById() available on Elements?

Most DOM query methods are available on both Documents and Elements. For example,

console.assert(
  document.getElementsByTagName   && document.body.getElementsByTagName &&
  document.getElementsByClassName && document.body.getElementsByClassName &&
  document.querySelector          && document.body.querySelector &&
  document.querySelectorAll       && document.body.querySelectorAll
);

However, getElementById is only available on Document:

console.assert(document.getElementById);
console.assert(document.body.getElementById == undefined);

Why is this so?


The WHATWG DOM Living Standard tells us that:

Web compatibility prevents the getElementById() method from being exposed on elements

The W3C DOM4 Recommendation is a bit more specific:

The getElementById() method is not on elements for compatibility with older versions of jQuery. If a time comes where that version of jQuery has disappeared, we might be able to support it.

However, I still have a hard time understanding what the issue could be. How could the presence of this methods adversely affect the behaviour of jQuery or other libraries?

I've tried looking through old versions of jQuery (such as 1.0.0 and 1.7.0) to see if any of their use of getElementById hints at why this may have been a problem. I see that getElementById used to be buggy in some older browsers, but they detect that and fall back to a reliable manual implementation instead. I don't see anywhere that it could be called on an element and cause a bug. Where does this compatibility concern come from?



from Why isn't getElementById() available on Elements?

No comments:

Post a Comment