Search code examples
javascriptcsscss-selectorsdouble-quotessingle-quotes

How to select an element that contains quote marks?


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.com/abc"def (yes, an attribute that contains quotes):

document.querySelector('img[src="http://www.example.com/abc"def"]');

It gets this error:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document':'img[src="http://www.example.com/abc"def"]' is not a valid selector.

Obviously, my question applies to both single ' and double " quote marks used simultaneously.


Solution

  • var test = document.querySelector('img[src="http://www.example.com/abc\\"def"]');`
    

    Appears to work, at least for me, on chrome, when I wrote this.