Javascript + queryselector support with all special characters with classname

Generally when using query selector in javascript we do like this,

<a href="http://www.test.com" class="abcd">ABCD</a>
var className = 'abcd';
var x = document.querySelector('.'+className);

It's working fine. Here, The className will be change generically. Example when I have classname with '/' had problem in that query selector

<a href="http://www.test.com" class="abcd/efgh">ABCD</a>
var className = 'abcd/efgh';
var x = document.querySelector('.'+className);

We get error like this

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '.abcd/efgh' is not a valid selector.

I understand the error due to classname have '/' , we can fix it using regular expression. But it;s possible to add the code for all special character support using regular expression or someother?

The classname is dynamically changes, So it comes with slash or anyother special character. It's possible to add the with all possible special characters.

Answers:

Answer

You can escape it using two backslashes (\\) in your js string (it'll be evaluated as \ and finally interpreted as an escape character by CSS parser).

var className = 'abcd\\/efgh';
var x = document.querySelector('.' + className);
console.log(x);
<a href="http://www.test.com" class="abcd/efgh">ABCD</a>

Source

Answer

Look at this answer. Which characters are valid in CSS class names/selectors? Character / is not allowed in css classes.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.