javascriptxmlcss-selectorsqueryselector

How to use `querySelector` to select an element whose label has a colon?


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:


Solution

  • 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');