How to fix a "not a valid selector" error when using a TailwindCSS classes in the selector for querySelectorAll?

789 Views Asked by At

I am trying to retrieve all DOM elements that match the following CSS selector using querySelectorAll():

let selector = 'div.group.w-ful.text-gray-800.dark:text-gray-100.border-b.border-black/10.dark:border-gray-900/50.dark:bg-gray-800 > div.text-gray-400.flex.self-end.lg:self-center.justify-center.mt-2.gap-2.md:gap-3.lg:gap-1.lg:absolute.lg:top-0.lg:translate-x-full.lg:right-0.lg:mt-0.lg:pl-2.visible';
let containerArray = document.querySelectorAll(selector);

However, when I run this code in the console, I get the following error:

1562:1 Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': 'div.group.w-ful.text-gray-800.dark:text-gray-100.border-b.border-black/10.dark:border-gray-900/50.dark:bg-gray-800 > div.text-gray-400.flex.self-end.lg:self-center.justify-center.mt-2.gap-2.md:gap-3.lg:gap-1.lg:absolute.lg:top-0.lg:translate-x-full.lg:right-0.lg:mt-0.lg:pl-2.visible' is not a valid selector.
    at <anonymous>:1:10

I'm not sure why this CSS selector is invalid. Can someone explain what's wrong with it and how I can fix it to make my querySelectorAll() work on the DOM?


Edit: I found out that : is an invalid character in CSS selectors. Escaping it with \ only does not work either. Invalid characters must be escaped with \\ in order to work with TailwindCSS classnames in .querySelectorAll():

let selector = 'div.group.w-ful.text-gray-800.dark\\:text-gray-100.border-b.border-black\\/10.dark\\:border-gray-900\\/50.dark\\:bg-gray-800 > div.text-gray-400.flex.self-end.lg\\:self-center.justify-center.mt-2.gap-2.md\\:gap-3.lg\\:gap-1.lg\\:absolute.lg\\:top-0.lg\\:translate-x-full.lg\\:right-0.lg\\:mt-0.lg\\:pl-2.visible';

This seems to work!

1

There are 1 best solutions below

1
gradient_dissent On

TailwindCSS class names make use of characters that aren't valid in CSS selectors. While this eases development, it leads to "not a valid selector" errors if not handled correctly.

When trying to use querySelectorAll() with CSS selectors including TailwindCSS classes, make sure to escape :, / and other invalid characters by prepending \\ to each of them.