0

If I call document.getElementsByClassName('cl'), I get a HTMLCollection. It seems to contain Element objects instead of HTMLElement objects, see Flow source, or Mozilla doc citing that it contains elements which are not HTMLElements. The W3C specification writes that HTMLCollection is a historical artifact, although I cannot seem to find any suggested alternative (what is 'Elements'?).

So should I check if returned object is indeed a HTMLElement? What else could it be and when? Or is there a better way to do what getElementsByClassName and similar methods do? (without using external libraries)

Thanks in advance!

3
  • XML elements would be my guess. Not everything is html anymore, so the removal of the name made sense at some point.
    – Vince
    Commented Oct 25, 2015 at 14:14
  • Yes I know that, but still, a HTMLDocument can only contain HTMLElements. Commented Oct 25, 2015 at 14:21
  • But in practice what those are and what they are implemented as might be subclasses of something else more generic and reusable.
    – uchuugaka
    Commented Oct 26, 2015 at 1:56

1 Answer 1

1

DOM is not HTML exclusive. XML and SVG (which is a form of XML) are also supported by the DOM specifications. Element is a general object that maps to a single element of any type.

Also, the alternative is a NodeList which is returned by querySelectorAll().

2
  • Great, querySelector() and querySelectorAll() were what I was looking for, thanks! Commented Oct 25, 2015 at 14:24
  • The querySelector functions requite a valid selector string so keep in mind the argument is different than the more specific getElement functions
    – uchuugaka
    Commented Oct 26, 2015 at 1:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.