Select elements by attributes with ":" (colon)
Asked Answered
D

5

19

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!

Dysphagia answered 14/7, 2017 at 20:9 Comment(2)
I think you need to escape the colon '[xml\\3A space]' see mothereff.in/css-escapesOutcaste
Perfect! Thank you so much!Dysphagia
O
18

You need to escape the colon

document.querySelectorAll('[xml\\3A space]')

I used https://mothereff.in/css-escapes to get the code above :)

Outcaste answered 14/7, 2017 at 20:21 Comment(0)
D
26

Escape the : by preceding it with a double backslash \\

document.querySelectorAll("[xml\\:space]")

See this:

https://bugzilla.mozilla.org/show_bug.cgi?id=883044

Dotti answered 14/7, 2017 at 20:15 Comment(1)
Not sure why this answer is linking to a Bugzilla report that has been rightfully closed as not a bug.Futhark
O
18

You need to escape the colon

document.querySelectorAll('[xml\\3A space]')

I used https://mothereff.in/css-escapes to get the code above :)

Outcaste answered 14/7, 2017 at 20:21 Comment(0)
C
4

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.

Compurgation answered 27/4, 2023 at 2:30 Comment(0)
S
0

try this

document.querySelectorAll('[*|space]')
Sommers answered 3/7, 2024 at 6:25 Comment(0)
W
-2

can also do

document.querySelectorAll('[id="xml:space"]')
Wirth answered 1/5, 2019 at 8:48 Comment(2)
Best option for when the id is dynamic.Vines
This is completely wrong and inapplicable: the question was about an attribute with the name xml:space, not an ID attribute with the value xml:space.Goring

© 2022 - 2025 — McMap. All rights reserved.