admin管理员组

文章数量:1356352

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.

Share Improve this question edited Jan 9 at 17:58 Barmar 784k57 gold badges548 silver badges660 bronze badges asked Aug 9, 2019 at 21:48 maxmax 1771 silver badge9 bronze badges 11
  • 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
 |  Show 6 more ments

3 Answers 3

Reset to default 8
var 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

本文标签: javascriptHow to select an element by an attribute value that contains quote marksStack Overflow