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>
source to share
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
.
source to share
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 fieldinnerHTML
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 margininnerHTML
or marginxml
. I have not been able to determine what could be behind these fields. There seems to be no other option other than using itXMLSerializer
for these browsers.
source to share
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. ...
source to share