简体   繁体   中英

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

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM