Reputation: 2170
In my project, there's a case where a library generates elements, and I need to select specific elements from there - which happen to contain an attribute with ":".
In other words, I ended up attempting to select using: document.querySelectorAll("[xml:space]")
.
But, when tested in Chrome, it didn't work, nor selecting using document.querySelectorAll("['xml:space']")
- they both threw a DOMException
:
https://i.sstatic.net/AHIeB.png
My question is, how to make the above selector return the list of the elements with xml:space
attribute?
Thanks!
Upvotes: 21
Views: 10419
Reputation: 1273
A more robust solution than only targeting colons specifically would be to use CSS.escape()
const query = CSS.escape("xml:space") // "xml\\:space"
document.querySelectorAll(`[${query}]`)
Note that we keep the square brackets outside of CSS.escape()
as those are not part of the attribute name and we want them to keep their semantic meaning in this selector.
Upvotes: 4
Reputation: 1826
You need to escape the colon
document.querySelectorAll('[xml\\3A space]')
I used https://mothereff.in/css-escapes to get the code above :)
Upvotes: 18
Reputation: 540
Escape the :
by preceding it with a double backslash \\
document.querySelectorAll("[xml\\:space]")
See this:
https://bugzilla.mozilla.org/show_bug.cgi?id=883044
Upvotes: 33