Search code examples
javascriptxmlinternet-explorer-11

What method should be used to read XML data in JavaScript?


I ran into a problem in my project where the values of XML nodes were returned as undefined in IE11 while they were returned as the expected valid values in all other browsers, including Edge.

To get the values I was using .innerHTML and after some research, I found out that .innerHTML doesn't work in IE11 and that technically it shouldn't be used to read XML node values in the first place.

I found a few solutions that all seemed hacky to me because they suggested using different methods of reading XML data for different browsers (aka IE11 and everything else). I figured there must be a standard way to read XML data that would work in all browsers since parsing XML is extremely common, not an obscure practice that would have different implementations in different browsers.

I finally found one video where a guy explained using .firstChild.data to read XML node values. I've implemented that in my project and it seems to work fine across all browsers. That's the only time I've come across this method. Everywhere else I looked suggested using .text(), .innerHTML, or .textContent (for IE11).

Is there a reason why .firstChild.data isn't or shouldn't be used and are there other methods that are cross browser compatible that are preferable?


Solution

  • If the firstChild is a text node, then you want to use nodeValue to access its text content. See also the textContent property.

    However, the firstChild may NOT be a text node, depending on your data. For example, given this XML document…

    <root><a><b>foo</b> bar</a></root>
    

    …the firstChild of the <a> element is an Element with text node child. So you would not want to use firstChild to find the text node.

    Further, data is specific to CharacterData interface. If you're sure you have a Text node, then you can use this property. Otherwise, I'd personally use the interfaces on Node itself until you know what type of node you have.