Tips on how to get away CSS selectors in JavaScript

Tips on how to get away CSS selectors in JavaScript

[ad_1]

Here is a trick query: how would you choose the next HTML part in JavaScript?

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

Oddly, this part’s identity is a #. However so far as I will inform, even supposing it is unusual it is nonetheless a superbly legitimate HTML characteristic. So, how would you question this part?

You undoubtedly may use the great previous file.getElementById()

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

This works, however I hardly ever use getElementById as it limits me to choose parts by the use of an identity. Duh! 😅

file.querySelector, alternatively, is extra versatile and permits any DOM part to be queried with a CSS selector.

However are you able to make a selection this “hash identity part” with a CSS selector the use of querySelector? Seems you’ll’t.

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

Sadly, ## is not a sound CSS selector, and I pay attention you are saying, “Come on Stefan, espace the second one # and you are just right to head!” and that is the reason proper, escaping the # persona works.

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

However have you learnt all of the characters that want to be escaped when you need to question a DOM part? Numerous legitimate HTML characteristic strings will throw an exception when used to question a DOM part.

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

Manually escaping characters is not a bulletproof resolution, however as of late I realized there is a at hand static manner within the CSS JavaScript namespace to assist with this precise downside — CSS.get away().

get away() means that you can safely use no matter characteristic values your HTML comprises.

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

Just right to understand!

You could surprise how frequently you need to take care of those strange characteristic values. As an example, the useId hook returns ids which can be invalid as CSS selectors. That is one case already, and I guess there are masses extra!

[ad_2]

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back To Top
0
Would love your thoughts, please comment.x
()
x