-1

In my code I am trying to get all classes which begin with priceList_ into an array for later use. the code I used to do that is: var prefix = document.querySelector('[class^="priceList_"]').className; There is one problem I am having with this code, which is that it only gives the first class with that prefix instead of giving an array of classes. Does anyone know the solution to this problem?

JasHam
  • 3
  • 2
  • 3
    Did u try ```querySelectorAll()```? – abellay Sep 28 '21 at 08:45
  • 1
    `.querySelector()` does not return "classes". It returns the first element that matches a given selector. Why do you want the classes in the first place? That seems... strange... – Andreas Sep 28 '21 at 08:47
  • @abellay thank you for the answer, I just tried out that code, but it returns an undefined value – JasHam Sep 28 '21 at 08:48
  • Its undefined because its a NodeList not a single item. To get the className you need to use a loop or access elements via their index – Reyno Sep 28 '21 at 08:48
  • 2
    [What do querySelectorAll and getElementsBy* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Andreas Sep 28 '21 at 08:49

4 Answers4

1

You need to be using document.querySelectorAll, document.querySelector purpose is to find the first element on the page matching the condition.

Just to add

document.querySelectorAll('[class^="priceList_"]').className

will error as the returned object is an NodeList of Nodes, not a singular Node (from which you'd be able to get the classe's).

If you wanted to obtain a structured array of each elements classe's then do the below

const classes = [...document.querySelectorAll('[class^="priceList_"]')].map(elem => elem.className);

This will assign an array of classe's (in the order of the DOM elements on the page). You could also do

const classes = [];

for (const elem of document.querySelectorAll('[class^="priceList_"]')) {

    classes.push(elem.className);
}

console.log('CLASSES', classes);
LoveDev
  • 257
  • 1
  • 9
1

querySelector() returns the first result, if you want multiple results use querySelectorAll().

FNER
  • 29
  • 5
0

Use querySelectorAll(), it gives NodeList. It is iterable.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Yevhenii Shlapak
  • 588
  • 2
  • 4
  • 13
  • 1
    thank you, I just tried it and someone told me to remove the .className which comes after, which made it work now without giving me undefined back – JasHam Sep 28 '21 at 08:53
0

Consider using Element.classList instead of className. You can also call classList.entries() to get an iterator.

You can also get an array from className with Element.className.split(" ")

classList on MDN Web Docs