How can I use querySelector
or any other JavaScript selector when the element's attribute contains quote marks "
?
For example, if I search for an img
element that has a src
of ;def
(yes, an attribute that contains quotes):
document.querySelector('img[src=";def"]');
It gets this error:
Uncaught DOMException: Failed to execute 'querySelector' on 'Document':'img[src=";def"]' is not a valid selector.
Obviously, my question applies to both single '
and double "
quote marks used simultaneously.
How can I use querySelector
or any other JavaScript selector when the element's attribute contains quote marks "
?
For example, if I search for an img
element that has a src
of http://www.example./abc"def
(yes, an attribute that contains quotes):
document.querySelector('img[src="http://www.example./abc"def"]');
It gets this error:
Uncaught DOMException: Failed to execute 'querySelector' on 'Document':'img[src="http://www.example./abc"def"]' is not a valid selector.
Obviously, my question applies to both single '
and double "
quote marks used simultaneously.
- escape it. do note however that it will require two backslashes. – Kevin B Commented Aug 9, 2019 at 21:52
-
2
All the url links can not have quotes by the standard, this characters MUST be urlencoded, so it's not actually
"
but%22
– Goran.it Commented Aug 9, 2019 at 21:52 -
What @Goran.it said.
<img src="http://www.example./abc"def">
is rendered like<img src="http://www.example./abc" def"="">
by Chrome – Mohrn Commented Aug 9, 2019 at 21:57 - @Goran.it eh, you're partly correct. querySelector's attribute equals selector is based on the attribute, not the property. the property does in fact get changed as you've stated, however, if it has an actual quote in the attribute, you'll need the quote in the attribute equals selector as well. – Kevin B Commented Aug 9, 2019 at 22:00
- 1 @Mohrn i mean, no html was provided, so we have no way of knowing that. It is possible to have quotes in an html attribute without it breaking the attribute the way you've described. – Kevin B Commented Aug 9, 2019 at 22:14
3 Answers
Reset to default 8var test = document.querySelector('img[src="http://www.example./abc\\"def"]');`
Escaping the quotes with \
appears to work.
You can use \ like this, JS should recognice that it's part of the string:
document.querySelector('img[src=\"http://www.example./abc\"def\"]');
Replace your quotes with &x22;
:
document.querySelector('img[src="http://www.example./abc&x22;def&x22;]');
Reference: James Donnelly's answer to How to Code Double Quotes via HTML Codes