Avi
Avi

Reputation: 2170

Select elements by attributes with ":" (colon)

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

Answers (5)

Matt
Matt

Reputation: 2290

try this

document.querySelectorAll('[*|space]')

Upvotes: 0

MarcusOtter
MarcusOtter

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

ofir_aghai
ofir_aghai

Reputation: 3281

can also do

document.querySelectorAll('[id="xml:space"]')

Upvotes: -2

Ted Whitehead
Ted Whitehead

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

Tucker David Grebitus
Tucker David Grebitus

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

Related Questions