Apollo Creed
Apollo Creed

Reputation: 219

Why can't I call getElementById on a javascript element?

Why does function getElementsByClassName() work on javascript objects, but "getElementById" kick back "not a function"?

var divBox= makeDivBox(divParams);
var divContents = divBox.getElementById("divID");

errors : divBox.getElementById is not a function

But :

var divContents = divBox.getElementsByClassName("divClass")[0];

has no issue. Why?

edit: see similar courtesy of @rajuGT

Upvotes: 0

Views: 1945

Answers (2)

jfriend00
jfriend00

Reputation: 707158

You appear to have a couple issues.

  1. divBox.getElementById("divID"); doesn't work because getElementById() is only a method on the document object. It is not a method on other types of objects. So, the divBox element does not have that method. You could use document.getElementById("divID") instead if there was only one divID in the entire document and if divBox was already inserted into the document.

  2. var divContents = divBox.getElementsByClassName("divClass")[0]; works because .getElementsByClassName() is a method on all DOM objects so it works when you call it on divBox.

You call getElementById() like this document.getElementById("someID").

If you want to find something in a particular part of the subtree, you can use element.querySelectorAll("#someID") or if you want to have more than one object with a given identifier, then you can use a class name and use functions that find objects with a given class name.

As to your specific questions:

divBox.getElementById is not a function

That is because geetElementById() is only a method on the document object and divBox is not a document object so it does not have that method, therefore you get the error you are seeing.

Why does this have no issue:?

var divContents = divBox.getElementsByClassName("divClass")[0];

That is apparently because divClass is a class name, not an id value and all HTML elements contain the getElementsByClassName() method so you can call it on divBox just fine.

Upvotes: 3

rajuGT
rajuGT

Reputation: 6404

It is because the id should be unique to the page/document.

So calling from the document and from the element should be same always. Hence providing the method for other DOM nodes is not useful at all and hence the getElementById is not available/added to the other DOM elements.

where as getElementsByClassName returns all DOM elements for the given className when called on document node. If called with any other DOM element, only child nodes which have the given className DOM nodes will be returned. Here, the behavior is different compared to the getElementById, hence this method is available to all DOM nodes.

Upvotes: 1

Related Questions