I'm learning vanilla js and something that keeps coming up is that I see some examples of code that say document.getElementBy... or document.getElement(s)By..., Is it the case that every html node has a corresponding js dom form where getElementBy refers to a single node and getElementsBy refers to a nodeList?
Do all html nodes have a "getElementsBy" and getElementBy" version?
Asked Answered
Principal element gathering methods from the DOM API are:
document.getElementById('[ID]')
// returns live HTML Element Objectdocument.getElementsByClassName('[CLASS]')
// returns live HTML Collection Objectdocument.getElementsByName('[NAME]')
// returns live HTML Collection Objectdocument.getElementsByTagName('[ELEMENT-TYPE]')
// returns live HTML Collection Object
and
document.querySelector('[CSS-SELECTOR]')
// returns static HTML Element Objectdocument.querySelectorAll('[CSS-SELECTOR]')
// returns static NodeList Object
[ELEMENT] should be [ID], [ELEMENT-TYPE] should be [TAGNAME] and [QUERY] should be [SELECTOR] (or [CSS-SELECTOR] if you prefer). querySelector() returns an Element just as getElementById() does, it does not return a single-element NodeList. –
Aveyron
Thanks, @BoltClock. Well caught. I've updated all except TAGNAME, because I get acid reflux when I hear elements referred to as "tags". –
Syman
But elements do have tag names. –
Fresher
© 2022 - 2024 — McMap. All rights reserved.
getElementsBy
andgetElementBy
version. If the desired element doesn't have an ID, you can use.getElementsByClassName
,.getElementsByTagName
,.getElementsByName
, etc. However, an element is not a node. – Minimusdocument
. – Pardon