For example, we have this XML:
<?xml version="1.0" encoding="UTF-8"?>
<xml xmlns:media="http://search.yahoo.com/mrss/">
<media:content></media:content>
</xml>
Then, how can I select the node whose label is foo:bar
using querySelector
in JavaScript?
A naive approach is like this:
const xml = new DOMParser().parseFromString(`
<?xml version="1.0" encoding="UTF-8"?>
<xml xmlns:media="http://search.yahoo.com/mrss/">
<media:content></media:content>
</xml>
`, 'text/xml');
const node = xml.querySelector('media\\:content');
However, after this, node
is null
.
Maybe related:
- https://bugzilla.mozilla.org/show_bug.cgi?id=883044
- Select elements by attributes with ":" (colon) (this one talks about when there is a colon in id)
- Select XML element with colon using plain JavaScript
(the answer suggests
getElementsByTagName
, but I want to usequerySelector
to have more flexibility)
There is a bug in your example. The first line must be the xml declaration.
Support for namespaces is not provided for the document.querySelector function.
You can use the non-namespaced selector to find the
content
element.