I have a html tag,
<div style="background-image: url("resources/images/test.jpg");"/>
I want to target this element using CSS selector. I tried below selector but its throwing error,
document.querySelector('*[style*="background-image: url("resources/images/test.jpg")"]')
Error: DOM Exception: SYNTAX_ERR (12)
I somehow have to escape double quotes around "resources/images/test.jpg". Please let me know if there is anyway I can escape it and target the tag.
The issue is not just in your selector string but also in your markup. The quotes in the url()
value are interfering with the style
attribute value resulting in invalid HTML. (The />
bit is invalid as well but that's not really relevant.)
Since you're dealing with a url()
value you can simply drop the quotes:
<div style="background-image: url(resources/images/test.jpg);">
Then amend your selector accordingly:
document.querySelector('*[style*="background-image: url(resources/images/test.jpg)"]');
On a side note I highly recommend trying to identify the element some other way, e.g. by using a class or constructing a selector based on the structure of your markup, instead of targeting the style
attribute, which is fragile. If you still need to test this style, you should just query the element's computed styles using window.getComputedStyle()
on the element after selecting it, since it's very likely that the inline style will be used.
If you cannot edit the markup, and what you have given in your question is exactly how it appears, then unfortunately you have invalid markup and it will be impossible for you to match this element, even with a valid selector.
If you absolutely must have the double quotes in the url()
value, you have a few options:
HTML-encode the inner quotes:
<div style="background-image: url("resources/images/test.jpg");">
Or swap the outer double quotes with single quotes so you don't have to HTML-encode anything:
<div style='background-image: url("resources/images/test.jpg");'>
To use the double quotes within the attribute selector:
You need to escape them twice: once for the selector, and again so it doesn't break the JavaScript string:
document.querySelector('*[style*="background-image: url(\\"resources/images/test.jpg\\")"]');
Alternatively, you can swap the quotes as above, although you will still need to escape the inner double quotes once so they don't break the string:
document.querySelector("*[style*='background-image: url(\"resources/images/test.jpg\")']");
You can also use single quotes in the url()
value, in which case you would need to follow the steps above, swapping the quotes as appropriate (except there is no need to HTML-encode anything). But as you can see, it's extremely complicated; if you can edit the markup, I'd honestly just drop the quotes entirely and avoid all of this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With