how to select element whose id contains | with jquery id selector

Viewed 241

If an element id is "mainid|label", it will throw exception when using $("#mainid|label").

Error: Syntax error, unrecognized expression: #mainid|label

Then how to get this element with jquery id selector?

3 Answers

You can also use $.escapeSelector

$("#"+$.escapeSelector("mainid|label"))

$.escapeSelector automatically manage every single special character present in your string

Since | is a meta character, you have to escape it

 $("#mainid\\|label")

Documentation

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar").

  1. Use the attribute selector

    Description: Selects elements that have the specified attribute, with any value.

console.log($('[id="mainid|label"]').text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='mainid|label'>mainid|label</span>

Related