-2

Class name:

var x = document.getElementsByClassName("intro");

CSS selector:

var x = document.querySelectorAll("p.intro");

I'm confused is there is any difference or both are same?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
dhruvv
  • 1
  • 1
  • 2
    The first also finds `div`s and other elements with `class="intro"`…!? – deceze Aug 24 '20 at 07:17
  • 1
    getElementsByClassName is a very old function and will work even before IE8 while querySelectorAll is more or less the later implementation of jQuery's $ function – Scriptkiddy1337 Aug 24 '20 at 07:19
  • 1
    Does this answer your question? [querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript](https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid) – Donald Duck Aug 24 '20 at 09:40

2 Answers2

2

document.getElementsByClassName("intro"); returns an array of html elements document.querySelectorAll("p.intro"); returns an array of nodes

And the difference between elements and nodes is explained here

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Terminat
  • 1,199
  • 5
  • 21
0

Class names are one type of CSS Selectors, we also have elements, ids, pseudo selectors and these can be combined in different ways. See a full list https://www.w3schools.com/cssref/css_selectors.asp

document.getElementsByClassName would only let you input class selectors document.querySelectorAll lets you use all and combine them in various ways just as you did with your p.intro

As pointed out, you can fine-tune the class selection by using multiple class names if that element possesses all.

  • "would only let you input one class selector" not sure what you mean by that. It allows for multiple classes. `document.getElementsByClassName("foo bar baz doo beee dooooo")` – epascarello Aug 26 '20 at 14:20
  • That is true, I meant in terms of specificity. I would edit that. Thank you – Bell Omuboye Aug 26 '20 at 14:30