-2

Maybe my questions are stupid because I am beginner in JavaScript

  1. Why is there is classList but there's not idList

  2. Why do some people prefer to use getElementById instead of getElementByClassName

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Ibrahim
  • 11
  • 4
  • 3
    1: how would you have an element with multiple IDs? 2: because they want to look up an element by its ID, not by its class – VLAZ Aug 24 '22 at 12:23
  • 1
    I prefer neither, `querySelector[All]` trumps both.. :) – Keith Aug 24 '22 at 12:29
  • IDs and classes are attributes on DOM elements. IDs must be unique to identify _one_ element in the page. An element can zero or more classes. – Andy Aug 24 '22 at 12:34
  • getElementById("id") is superior to querySelector("#id") due to the specificality of the ID – mplungjan Aug 24 '22 at 12:39
  • @mplungjan Could you elaborate on what you mean by, specificality of the ID? – Keith Aug 24 '22 at 12:43

2 Answers2

0

Question 1: Every element can only have 1 id so there is no need for a list.

Question 2: getElementByClassName is not a function. getElementsByClassName is (notice the plural "elements"). getElementsByClassName returns a list of elements while getElementById returns only one element. Use getElementsByClassName is better when you want to get multiple elements.

I would recommend querySelector and querySelectorAll. They take CSS selector queries instead.

Joseph Tams
  • 63
  • 1
  • 5
  • 1
    Worth mentioning the difference between methods like `getElementsByClassName` and `querySelector` - the former returns a live HTML collection, the latter a static (non-live) node list. – Andy Aug 24 '22 at 12:38
  • 3
    @Andy you mean querySelectorAll – mplungjan Aug 24 '22 at 12:39
0

Question 1: Every element can only have one id, hence there is no requirement for an idList.

Question 2: You can read this . However, there are times where the id selector can outperform the class selector in speed. Which one to use (getElementById or getElementsByClassName) in these circumstances is up to you.

barankibar
  • 56
  • 1
  • 13