Friday, October 10, 2025
HomeJavaScriptFind out how to escape CSS selectors in JavaScript

Find out how to escape CSS selectors in JavaScript


This is a trick query: how would you choose the next HTML factor in JavaScript?

<div id="#">Choose me!</div>

Oddly, this factor’s id is a #. However so far as I can inform, regardless that it is unusual it is nonetheless a superbly legitimate HTML attribute. So, how would you question this factor?

You certainly might use the nice previous doc.getElementById()

console.log(doc.getElementById('#')); 

This works, however I not often use getElementById as a result of it limits me to pick parts by way of an id. Duh! 😅

doc.querySelector, however, is extra versatile and permits any DOM factor to be queried with a CSS selector.

However can you choose this “hash id factor” with a CSS selector utilizing querySelector? Seems you may’t.

console.log(doc.querySelector('##'));

Sadly, ## is not a sound CSS selector, and I hear you say, “Come on Stefan, espace the second # and also you’re good to go!” and that is proper, escaping the # character works.

console.log(doc.querySelector('##')); 

However have you learnt all of the characters that must be escaped whenever you wish to question a DOM factor? Loads of legitimate HTML attribute strings will throw an exception when used to question a DOM factor.

doc.querySelector('.a:b');     
doc.querySelector('[href=@]'); 
doc.querySelector('.[jooo]');  

Manually escaping characters is not a bulletproof answer, however right now I discovered there is a useful static technique within the CSS JavaScript namespace to assist with this actual downside — CSS.escape().

escape() means that you can safely use no matter attribute values your HTML consists of.

console.log(`.${CSS.escape('a:b')}`);      
console.log(`[href=${CSS.escape('@')}]`); 
console.log(`.${CSS.escape('[jooo]')}`);  

Good to know!

You may surprise how typically it’s a must to cope with these uncommon attribute values. For instance, the useId React hook returns ids which are invalid as CSS selectors. That is one case already, and I wager there are a lot extra!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments