0

I'm having a hard time figuring out why my expression is unrecognised.

My html element looks like that:

<tr class="beampower_01/target_surface_01-child shown">(...)</tr>

I'm trying to access that with expression:

$('.' + $(elemClicked).attr("path")+ '-child');

expression:

console.log($(elemClicked).attr("path"))

results with:

beampower_01/target_surface_01

The error I receive is:

Uncaught Error: Syntax error, unrecognized expression: .beampower_01/target_surface_01-child

Where is the error?

Malvinka
  • 1,185
  • 1
  • 15
  • 36
  • 2
    `/` is not valid in a class name, so it's not valid in the selector – freedomn-m Nov 13 '20 at 10:39
  • Does this answer your question? [jQuery syntax error, unrecognised expression](https://stackoverflow.com/questions/34123815/jquery-syntax-error-unrecognised-expression) (found by searching your exact title) – freedomn-m Nov 13 '20 at 10:40

1 Answers1

2

While beampower_01/target_surface_01-child is a valid class name to put on an element (see here and here), .beampower_01/target_surface_01-child is an invalid CSS class selector. Class names in class selectors must be CSS identifiers:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".

(That's the language from the old 2.1 spec, which is convenient for quoting. The valid characters haven't changed, see here and here in the modern spec.)

You can't have an unescaped slash like that.

I'd strongly recommend not using slashes in class names, so that you don't have to deal with trying to escape them. But you can escape them by adding a backslash in front:

$('.' + $(elemClicked).attr("data-path").replace(/\//g, "\\/") + '-child')

Live Example:

$("input[type=button]").on("click", function() {
    const elemClicked = this;
    $('.' + $(elemClicked).attr("data-path").replace(/\//g, "\\/") + '-child')
.css("color", "blue");
});
<table>
    <tbody>
          <tr class="beampower_01/target_surface_01-child shown">
              <td>Hi there</td>
          </tr>
    </tbody>
</table>

<input type="button" data-path="beampower_01/target_surface_01" value="Click me">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875