Is prototyping getElementById chaining appropriate?

By chaining I mean,

var elementParent = document.getElementById('parentContainer');

elementParent.getElementById('uniqueChild');

This doesn’t work by itself, but I looked up answers and saw:

Element.prototype.getElementById = function(id) {
  return document.getElementById(id);
};

Which through prototyping enables this kind of unique object linking. I am not using it, just found it curious and being a bit cautious, would it be wise to use something like this for…well anything at all? Or is it a dangerous hack that promotes improper HTML syntax(spamming the same Id across one page)?

I just don’t get the point. Why not use a class?

Just a question. I clearly said I don’t use it. Just wondering why this is a thing to begin with and what possible purpose it could have.

1 Like

It doesn’t make much sense for getElementById because you can only have one id in the page.

http://prototypejs.org/ famously extended the object prototypes like Element, it works but is generally considered bad practice these days.

Polyfills use them frequently though to fill in the gaps in older browsers. e.g.

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

This lets you use " asdf ".trim() in browsers that don’t have that function on strings.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.