Why does getElementById not work with elements other than a document?

Why do document.body.getElementById(idOfElem)and document.body.getElementsByName(nameOfElem)do not work?

and

Why do document.body.getElementByTagName(tagOfElem)they document.body.getElementByClassName(classOfElem)work?

On first use, the browser throws this error:

TypeError: document.body.getElementById is not a function [Details]

+4
source share
3 answers

Since the identifiers are unique, you should use document.getElementById, as this is the only DOM element that has this feature.

Elements other than documenthave the following functions: getElementsByTagName, getElementsByClassName, querySelectorand querySelectorAll, but not getElementById.

Why not define it on elements other than the document?

. , , . , getElementById , document.

?

<div> <p> .cls, . , document , , , .

:

document.getElementById , DOM ( ). , getElementsByTagName, getElementByClassName,... , . , , , .

+3

getElementById - document, document.body. getElementsByName.

, getElementByTagName getElementByClassName , body.

+2

document.body.getElementById()does not exist. Usage document.getElementById()gets an element with a match identifier from the document.

document.getElementsByTagName() - gets all the elements that match the tag name from the document.

0
source

Source: https://habr.com/ru/post/1669399/


All Articles