-1

I'm aware this isn't "best practice" but I'm curious why this code doesn't work. For reference, I'm using Chrome 63 at the moment.

Typing getElementById everywhere is obnoxious. Suppose I have the following code:

var D = document;
D.getID = D.getElementById;
D.getTags = D.getElementsByTags;
HTMLElement.prototype.getID = HTMLElement.prototype.getElementById;
HTMLElement.prototype.getTags = HTMLElement.prototype.getElementsByTags;

If I try to use these new names, e.g. D.getID("foo").getID("bar"), then I get the error D.getID("foo").getID("bar") is not a function. What's the deal? (To be sure, D.getID("foo") works just fine)

junius
  • 570
  • 3
  • 14
  • https://stackoverflow.com/questions/954417/make-alias-to-document-getelementbyid-in-javascript – epascarello Mar 02 '18 at 20:16
  • Why do you need ...getId('bar'); ? D.getId('foo') or D.getId('bar') should be sufficient. – D. Braun Mar 02 '18 at 20:19
  • @epascarello that doesn't answer the question. I need a solution to the problem of aliasing the method for HTML Elements as well. – junius Mar 02 '18 at 20:26
  • @D.Braun kind of a contrived example. It doesn't work with `getElementsByTags` either. – junius Mar 02 '18 at 20:26
  • @KevinKeith There's no function called `getElementsByTags`. It's `getElementsByTagName` – Barmar Mar 02 '18 at 20:29
  • `HTMLElement` doesn't have a `getElementById` method, it only exists for the `Document` element. So `HTMLElement.prototype.getElementById` is undefined. – Barmar Mar 02 '18 at 20:33
  • @KevinKeith I am guessing you did not look at all the answers. The second on used bind() which is what you needed to do. – epascarello Mar 02 '18 at 23:37

1 Answers1

1

Since IDs are supposed to be unique in a document, there's no HTMLElement.prototype.getElementById() method. The only object that has this method is document.

You can add this method to HTMLElement by assigning the function that's bound to document:

HTMLElement.prototype.getID = document.getElementById.bind(document);

Note that even though you can use this to call the method from a particular element, it will search the entire document, not just within that element. You could use querySelector to limit it:

HTMLElement.prototype.getID = function(id) {
    return this.querySelector('#' + id);
}

Your code for getTags just uses the wrong name for the long method. It should be:

HTMLElement.prototype.getTags = HTMLElement.prototype.getElementsByTagName

There's no need for the assignments to D.getID and D.getTags, since Document inherits from HTMLElement.

Barmar
  • 741,623
  • 53
  • 500
  • 612