Reputation: 926
I have a webpage which contains such code:
<img class="img-qrcode" id="img_123.000.00.01"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:
$("#img_123.000.00.01")
The added screenshot shows that it returns an empty array.
Why does it not find the element with ID ?
Upvotes: 1
Views: 73
Reputation: 959
Since #id.className
is a valid selector jQuery assumes it so and tries to find such element. In your case you will have to escape the dot.
Change $("#img_123.000.00.01")
to $("#img_123\\.000\\.00\\.01")
and it will work.
Official jQuery documentation(https://api.jquery.com/category/selectors/) states it clearly.
To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?@[\]^
{|}~` ) as a literal part of a name, it must be escaped with with two backslashes
Upvotes: 0
Reputation: 7082
Using an attribute selector for id
, you don't have to worry about escaping the class selector (.
)
let img = $("img[id='img_123.000.00.01']");
console.log(img.attr('src'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123.000.00.01"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
Upvotes: 2
Reputation: 1179
When some special symbols are in the jquery selector, you need to add 『\\』
console.log($("#img_123\\.000\\.00\\.01"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<img class="img-qrcode" id="img_123.000.00.01" src="http://localhost:7777/data/code_img\123.000.00.01.png" alt="./data/code_img\123.000.00.01.png" style="display:none">
</body>
</html>
Upvotes: 0
Reputation: 16575
Find with ^
let img = $("img[id^='img_123']");
console.log(img.attr('src'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="img-qrcode" id="img_123"
src="http://localhost:7777/data/code_img\123.000.00.01.png"
alt="./data/code_img\123.000.00.01.png" style="display:none">
Upvotes: 0
Reputation: 943211
The a .
character has special meaning in a selector (it starts a class selector) so you need to escape it. (Remember to escape the slash character in a string literal).
Generally it is easier to just avoid using .
chapters in an id.
Upvotes: 1