I have a code that creates a CSS selector by traversing through the dom to that particular element, but here lies the case I use tailwind, and sometimes the tailwind classes are causing a problem for me so I don’t tend to get the element in the dom. For example something like this: class="about_hero_text max-w-[530px] py-[15px] px-0 md:mt-3 md:px-6"
produces something like this "div.about_hero_text.max-w-5b 530px5d.py-5b 15px5d.px-0.md3a mt-3.md3a px-6"
which as you can see is not right.
const oldSelector =
'section#shopify-section-template--18077714481441__main > div.about-hero-wrapper.flex.justify-center.gap-x-5 > div.px-4.md3a px-6 > div.about_hero_text.max-w-5b 530px5d.py-5b 15px5d.px-0.md3a mt-3.md3a px-6 > div.about-hero-adb > a';
const newValidSelector =
'section#shopify-section-template--18077714481441__main > div.about-hero-wrapper.flex.justify-center.gap-x-5 > div.px-4 > div.about_hero_text > div.about-hero-adb > a';
If you look at these two selectors you can see a pattern where I’ve removed some classes from it to make the selector valid and actually recognize it in the dom. can you detect the pattern or can I have a function that cleans it up? I have a function which needs improvement.
function fixSelector(oldSelector) {
const classPattern = /(.[wd-]+)(?=s|..*?s|$)/g;
const modifiedSelector = oldSelector.replace(classPattern, '');
return modifiedSelector.trim();
}
const oldSelector = 'section#shopify-section-template--18077714481441__main > div.about-hero-wrapper.flex.justify-center.gap-x-5 > div.px-4.md3a px-6 > div.about_hero_text.max-w-5b 530px5d.py-5b 15px5d.px-0.md3a mt-3.md3a px-6 > div.about-hero-adb > a';
const newValidSelector = fixSelector(oldSelector);
console.log(newValidSelector); // i want something like this 'section#shopify-section-template--18077714481441__main > div.about-hero-wrapper.flex.justify-center.gap-x-5 > div.px-4 > div.about_hero_text > div.about-hero-adb > a';
2
Answers
I've been able to generate this code which works just fine
Before
After
First, the regular expression pattern classPattern now captures the Tailwind classes more accurately. It matches any class starting with a dot
(.[wd-]+)
.Next, I’ve added a new step where we extract all the classes that need to be removed from the oldSelector using match(classPattern). If no classes are found, we default to an empty array.
Then, I use reduce to iterate over the classesToRemove array and replace each class with an empty string in the modifiedSelector. This ensures that all the Tailwind classes are removed.
Finally, the function returns the trimmed modifiedSelector, providing you with the desired valid selector.