Search code examples
javascriptjqueryxmlinnerhtmljquery-xml

innerHTML missing when XML parsing with jQuery in IE9 but not Chrome


I'm using jQuery's XML parser on some simple content that contains HTML.

Extracting the full HTML text using jQuery's .html() or standard javascript .innerHTML works fine in Chrome, but not in Internet Explorer 9. jQuery's .text() works in both cases, but I need the html tags extracted as well.

How can I make it work with IE9 as well?

You can test it out here: http://jsfiddle.net/199vLsgz/

XML:

<script id="xml_data" type="text/xml">
    <model_data name="The model ">
          <person_responsible></person_responsible>
          <objects>
               <object name="Available B reports" id="obj1" >
                   <description>this is a description <br/> oh look, another line!</description>
               </object>
          </objects>
     </model_data>
</script>

Code:

$(function() {

    var xml = $("#xml_data").text();
    var xmlDoc = $.parseXML(xml);
    $xml = $(xmlDoc);

    var desc = $xml.find("model_data > objects > object[id='obj1'] > description");
    alert(desc.html());

})

Solution

  • Xml elements do not have innerHTML defined inside IE which is what's being used with the html function of jquery.

    Firstly you need to use CDATA to preserve tags inside xml tags

    <description><![CDATA[this is a description <br/> oh look, another line!]]></description>

    then you can try to use the textContent property:

    alert(desc[0].textContent); //desc.text() will also work now
    

    And you also can add the content correctly using something like:

    $('#some-container').html(desc[0].textContent);
    

    $(function() {
    
        var xml = $("#xml_data").text();
        var xmlDoc = $.parseXML(xml);
        $xml = $(xmlDoc);
        console.log($xml)
        var desc = $xml.find("model_data > objects > object[id='obj1'] > description");
        alert(desc[0].textContent);
    
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script id="xml_data" type="text/xml">
        <model_data name="The model">
              <person_responsible></person_responsible>
              <objects>
                   <object name="Available B reports" id="obj1" >
                       <description><![CDATA[this is a description <br/> oh look, another line!]]></description>
                   </object>
              </objects>
         </model_data>
    </script>