Skip to content
Advertisement

How can I use document.querySelector to select this class name with a space in it?

JavaScript

I have been using

JavaScript

But now, the class name has changed: there’s a space and some new text in the class name:

JavaScript

How can I change el = document.querySelector(".PrmryBtnMed"); to find the right class?

I tried using el = document.querySelector(".PrmryBtnMed.ApricotWheat"); but that didn’t work.

Next, I tried to add a space (and escape using a backslash): el = document.querySelector(".PrmryBtnMed ApricotWheat"); but that didn’t work either.

So, I wondered if I could use %20 for the space.. but no luck.

I’d be very grateful for some help! What am I doing wrong?

Advertisement

Answer

Classes can’t have spaces, what you have there is an element with two separate classes on it. To select an element with two classes, you use a compound class selector:

JavaScript

That selects the first element in the document that has both the PrmryBtnMed class and the ApricotWheat class. Note that it doesn’t matter what order those classes appear in in the class attribute, and it doesn’t matter whether there are also other classes present. It would match any of these, for instance:

JavaScript

or

JavaScript

or

JavaScript

etc.

Also note that the quotes you’re using around HTML attributes are sporatically invalid; the quotes around attributes must be normal, boring, single (') or double ("), they can’t be fancy quotes.

Live example with quotes fixed and using the selector above:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement