44

If you use getElementById to with document like - document.getElementById then it always works.

But however, if we perform the same on an element say x like x.getElementById, then it returns an error.

The unusual thing about this is that getElementsByClassName and getElementsByTagName work on the elements however getElementById doesn't!

akash4eva
  • 815
  • 1
  • 6
  • 11

1 Answers1

66

Container IDs should be unique, so there's no reason to find an object by ID within another container. This is why you only need document.getElementById to access any element by its ID, whereas when you are searching by class or tag name, you might want to only search within a specific container, which is why you can do x.getElementsByClassName etc.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
mash
  • 14,851
  • 3
  • 30
  • 33
  • @cantera you should not have multiple elements with the same ID on one page. That is not what an ID is for. IDs should be unique. – mash Feb 18 '15 at 00:45
  • ID's do not need to be unique. Getting a comma separated list of values may be very important. – Marc Johnston May 15 '15 at 21:42
  • Also ... when an element is cloned ... finding a child of that clone is helpful if it supported getElementById. – Marc Johnston May 15 '15 at 21:43
  • 33
    @mash Nobody is saying he's duplicating IDs. You could have something like `
    `. If you already have `article1` in a JavaScript variable, it would be useful to use `article1.getElementById("article1Image")` instead of searching through the document all over again.
    – M - May 11 '16 at 20:29
  • 10
    It's worth noting that, the element you're attempting to get is not always in the DOM, thus one can't use `document.getElementById`. A use case of this would be AJAX loading HTML into a variable instantiated by `#createElement` and from there attempting to extract elements with specific IDs. – Kodlee Yin Sep 07 '16 at 03:31
  • You could so something like this: `element.querySelector('foo[id=bar]')` where _foo_ is the tag name, and _bar_ is the element id. – basiphobe Oct 21 '16 at 17:04
  • 1
    @basiphobe that selector can be just reduced to `#bar`. – mash Oct 22 '16 at 01:36
  • Good point, @mash. – basiphobe Dec 30 '16 at 19:52
  • 3
    Well, in my case I only wanted to select the element (by ID) _if_ it was inside another element, I ended up switching to `el.querySelector('#' + id)` instead of `el.getElementById(id)` – powerbuoy Feb 16 '17 at 12:37
  • @MarcJohnston `id`s _do_ need to be unique. Most browsers are pretty forgiving if you overlook this, but that doesn’t mean duplicating the `id` is correct. That’s why the method name is singular (`getElementById`) and that’s why it will only return a single value. If you’re desperate to find _all_ elements with the same `id`, you could try `document.querySelectorAll(…)`. – Manngo Nov 17 '17 at 09:40