1

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.

RSKMR
  • 1,812
  • 5
  • 32
  • 73
  • How are you fixing the error for `/` and why ? – bitsapien Sep 20 '17 at 12:29
  • 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. – RSKMR Sep 20 '17 at 13:05

2 Answers2

3

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

Serge K.
  • 5,303
  • 1
  • 20
  • 27
1

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

nikitar
  • 31
  • 3
  • 2
    You should not reference such old posts when specifications have changed. The [*current HTML specification*](http://w3c.github.io/html/dom.html#element-attrdef-global-class) says: "*When specified on HTML elements, the class attribute must have a value that is a set of space-separated tokens representing the various classes that the element belongs to. ... There are no additional restrictions on the tokens authors can use in the class attribute…*". In other words, you can use any characters you like, but space will be treated as a separator. – RobG Sep 20 '17 at 12:34