1

I'm trying to select an element this way

$('#QR~QID345')

because the element's id is QR~QID345 but the selector doesn't work with ~, is there any fix?

Changing the id is not an option in this case.

Barskey
  • 423
  • 2
  • 5
  • 18
afdi2
  • 89
  • 10

2 Answers2

6

You can escape ~ with \\

alert( $('#QR\\~QID345').text() );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="QR~QID345">Hello</div>
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24
3

You can use $.escapeSelector to escapes any character that has a special meaning in a CSS selector.

var id = $.escapeSelector("QR~QID345");

console.log($('#' + id).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="QR~QID345">
  Hello World
</p>

As been noted by Rory McCrossan on the comment, $.escapeSelector was added on version 3.0

Doc: $.escapeSelector()

Eddie
  • 26,593
  • 6
  • 36
  • 58