Does innerHTML work with XML elements?

According to JavaScript: The Definitive Guide: "Despite its name, innerHTML can be used with XML elements as well as HTML elements."

However, when I actually try to access the innerHTML property of the XML Element object, it returns undefined

:

var xml = $.ajax({url: "test.xml", async: false}).responseXML.documentElement;
console.log(xml.innerHTML); // displays "undefined" in console log

      

What is the explanation for this behavior?

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<foo><bar>baz</bar></foo>

      

+2


source to share


4 answers


The explanation is that the book is wrong at this point.



XML elements in IE have a custom property xml

that provides an equivalent innerHTML

. For other browsers, you need to use XMLSerializer

.

+6


source


Earlier answers do not address new browsers that have been around since September 2014. When an XML document is created with

var parser = new DOMParser(); 
var doc = parser.parseFromString(data, "text/xml");

      



where data

is an XML document as a string, then the following conditions are met:

  • In Firefox 28 and Chrome 36, nodes in doc

    have a field innerHTML

    that contains the XML serialization of the node's content.

  • In IE 9, 10 and 11, Safari 7.0 and Opera 12, nodes in doc

    have no margin innerHTML

    or margin xml

    . I have not been able to determine what could be behind these fields. There seems to be no other option other than using it XMLSerializer

    for these browsers.

+5


source


HTML5 defines there innerHTML in XML elements (despite the name, using XML parser / serializer). Nothing is being implemented yet. Opera has supported innerHTML in XHTML for a while (albeit not in XML format), but uses an HTML parser / serializer to do so.

+2


source


You can do this, but I would rather use jQuery because it is easier to implement. The jQuery way is to select the container of elements you want. Then you can use the html () property to change or get the innerHTML of your element.

$("myxmltag").html("<achildtag>Hello</achildtag><anotherchildtag>World!</anotherchildtag>");

      

For more information on this property refer to: http://api.jquery.com/html/

Also, don't forget about the differences between html () and text () and you can use other properties to manipulate elements inside a node in your xml with jQuery, like append (), prepend (), after (), etc. ...

-1


source







All Articles