Do all html nodes have a "getElementsBy" and getElementBy" version?
Asked Answered
Y

1

6

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?

Year answered 7/8, 2017 at 20:27 Comment(4)
In short, yes, all elements have a getElementsBy and getElementBy version. If the desired element doesn't have an ID, you can use .getElementsByClassName, .getElementsByTagName, .getElementsByName, etc. However, an element is not a node.Minimus
no. All element nodes however do. developer.mozilla.org/en-US/docs/Web/API/Element vs developer.mozilla.org/en-US/docs/Web/API/NodePardon
Just for whatever it's worth, those APIs are not "vanilla JavaScript", they're "vanilla web browser APIs". They're not part of the JavaScript language.Brunet
There are also exceptions, such as getElementById only being available on document.Pardon
S
7

Principal element gathering methods from the DOM API are:

  • document.getElementById('[ID]') // returns live HTML Element Object
  • document.getElementsByClassName('[CLASS]') // returns live HTML Collection Object
  • document.getElementsByName('[NAME]') // returns live HTML Collection Object
  • document.getElementsByTagName('[ELEMENT-TYPE]') // returns live HTML Collection Object

and

  • document.querySelector('[CSS-SELECTOR]') // returns static HTML Element Object
  • document.querySelectorAll('[CSS-SELECTOR]') // returns static NodeList Object
Syman answered 8/8, 2017 at 13:9 Comment(3)
[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.