does innerHTML work with XML Elements?
According to JavaScript: The Definitive Guide: "Despite its name, innerHTML can be used with XML ele开发者_如何学Goments as well as HTML elements".
However, when I actually attempt to access the innerHTML property of an XML Element object, undefined
is returned:
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>
The earlier answers don't address the newer browsers that exist as of September 2014. When an XML document is created with:
var parser = new DOMParser();
var doc = parser.parseFromString(data, "text/xml");
where data
is the XML document as a string, then the following are true:
In Firefox 28, and Chrome 36, the nodes in
doc
have aninnerHTML
field that contains the XML serialization of the contents of the node.In IE 9, 10 and 11, Safari 7.0 and Opera 12, the nodes in
doc
have neither aninnerHTML
field nor anxml
field. I was not able to identify something that could stand for these fields. There does not appear to be any other option than usingXMLSerializer
for these browsers.
The explanation is that the book is wrong on this point.
XML elements in IE have a non-standard xml
property that provides the equivalent of innerHTML
. For other browsers you'll need to use an XMLSerializer
.
HTML5 defines there to be innerHTML on XML Elements (despite the name, using XML parser/serializer). Nothing implements this yet. Opera has for a while supported innerHTML in XHTML (though not XML generally), but uses the HTML parser/serializer for it.
You can do so, but I'd rather prefer to use jQuery because it is easier to implement. The jQuery way is selecting the element container that 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 about this property, refer to: http://api.jquery.com/html/
Also, don't forget the differences between html() and text(), and you can use other properties to manipulate the elements within a node in your xml using jQuery, like append(), prepend(), after(), etc...
精彩评论