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!