当元素的属性包含引号"
时,如何使用img
或任何其他Javascript选择器?
例如,如果我搜索一个src
为http://www.example.com/abc"def
的{{1}}元素(是的,包含引号的属性):
document.querySelector('img[src="http://www.example.com/abc"def"]');
出现此错误:
Uncaught DOMException: Failed to execute 'querySelector' on 'Document':'img[src="http://www.example.com/abc"def"]' is not a valid selector.
很明显,我的问题适用于同时使用的单引号'
和双引号"
。
答案 0 :(得分:3)
var test = document.querySelector('img[src="http://www.example.com/abc\\"def"]');`
我写这篇文章时,似乎至少对我来说是在chrome上工作。
答案 1 :(得分:0)
用&x22;
代替引号document.querySelector('img[src="http://www.example.com/abc&x22;def&x22;]');
答案 2 :(得分:0)
您可以像这样使用\,JS应该识别出它是字符串的一部分:
document.querySelector('img[src=\"http://www.example.com/abc\"def\"]');