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:
getElementsByTagName
, but I want to use querySelector
to have more flexibility)There is a bug in your example. The first line must be the xml declaration.
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');
Support for namespaces is not provided for the document.querySelector function.
You can use the non-namespaced selector to find the content
element.
const node = xml.querySelector('content');