views:

1092

answers:

3

I've a xml file in which I'm storing some HTML content in an element tag called <body>. Now I'm trying to read all the HTML content of body tag using XML DOM in JavaScript.

I tried this code:

var xmlDoc=loadXMLDoc('QID_627.xml');
var bodytag = xmlDoc.getElementsByTagName("body");
document.write(bodytag);

but it is showing [object HTMLCollection] message on the browser screen.

A: 

You need to use document.write(bodytag.toXMLString());

EDIT: Andrew Hare also points out you need to subscript first. I think you may still need to use the toXMLString call as well.

Jesse Rusak
+2  A: 

Try this:

var xmlDoc=loadXMLDoc('QID_627.xml');
var bodytags = xmlDoc.getElementsByTagName("body");
document.write(bodytags[0]);

getElementsByTagName returns an array of elements (even if just one is found) so you need to subscript the array to retrieve your element.

Andrew Hare
+1  A: 

Andrew Hare pointed out that getElementsByTagName() always returns an array, so you have to use bodytag[0] to get the element you want. This is correct, but not complete since even when you do that you'll still get an equally useless "[object ElementName]" message.

If you're set on using document.write() you can try to serialize out the content of the body tag with

 document.write(bodytag[0].innerHTML);

Better yet would be directly attaching the source DOM nodes into your destination DOM.

You'd use something like

document.getElementById("destinationNodeId").appendChild(bodytag[0]);

There may be some issues with attaching DOM nodes from another document that may require you to copy the nodes, or jump through some other hoops to have it work.

Peter Dolberg