I hope you can read my code, I have an XML file on my localhost and I would like it to pull the title and year from that file (it currently has Title, Year, Artist, Price, and Country) while maintaining the H1 and button on the page.
The H1 text and button disappear onClick and I would like it to remain on the same page as the results.
<h1>Show the Album list</h1>
<script>
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","cd_catalog.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
function CdCatalog()
{
document.write("<table border='1'><th>TITLE</th><th>YEAR</th>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
}
</script>
The problem is that you’re using
document.writefor a button’s click event, which is after the document’s been closed…which means it overwrites everything. Since your page is simple and only has an<h1>and button, it looks like only those things are being hidden, but it would be everything on the page (if you had more).The solution is to use
.appendChildand/or.innerHTMLto add the content dynamically. I’ll provide a solution in a minute 🙂UPDATE:
Since you’re using tables, you might as well use the native methods
.insertRowand.insertCellthat make table creation much easier. Here’s an example of what you could use overall:And unless I’m mistaken, you can’t nest
<td>inside of<table>…you must nest them in<tr>…which are nested in<table>