function loadDoc() {
/*
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "URL OF SERVER", true);
xhttp.send();
*/
// manually invoking myFunction because I don't have a xhr
myFunction();
}
function myFunction(xml) {
var i;
var option;
// var xmlDoc = xml.responseXML;
var xmlDoc = getFakeXml();
var table = "<tr><th>TYPE</th><th>MAKE</th><th>PRICE</th><th>MODEL</th><th>ID</th><th>Select</th></tr>";
document.getElementById("dem").innerHTML = table;
var x = xmlDoc.getElementsByTagName("itemnumber");
for (i = 0; i < x.length; i++) {
// let's create a TR element for each itemnumber
var row = createRow(x[i]);
// appending the created row to your table :
document.getElementById("dem").appendChild(row);
}
}
function createRow(rowData) {
// local variables :
var tr, item = {};
// create the TR element
var tr = document.createElement("tr");
// for each field, retrieving data from rowData
item.type = getField(rowData, "type");
// and adding a cell to the row :
addCell(rowData, item.type, tr);
item.make = getField(rowData, "make");
addCell(rowData, item.make, tr);
item.price = getField(rowData, "price");
addCell(rowData, item.price, tr);
item.model = getField(rowData, "model");
addCell(rowData, item.model, tr);
item.id = getField(rowData, "id");
addCell(rowData, item.id, tr);
// creation of the button element, to be able to add a unique event listener to it :
var button = document.createElement("button");
button.innerHTML = "Add item to cart";
button.onclick = function() {
/* code your event handler here
it has access to all the data retrieved from rowData
*/
console.log("adding element to cart", item);
}
tr.appendChild(button);
return tr;
}
function getField(rowCell, fieldName) {
var data = rowCell.getElementsByTagName(fieldName)[0].childNodes[0].nodeValue;
return data;
}
function addCell(rowCell, data, row) {
var cell = document.createElement("td");
cell.innerHTML = data;
row.appendChild(cell);
}
/* this is a just a function returning some fake XML. Only needed for this snippet */
function getFakeXml() {
var xmlString = `<root><itemnumber>
<type>Smartphone</type>
<make>Nokia</make>
<price>14000.0</price>
<model>Lumia830</model>
<id>S00010</id>
</itemnumber>
<itemnumber>
<type>Smartphone</type>
<make>Samsung</make>
<price>10000.0</price>
<model>Galaxy A5</model>
<id>S00002</id>
</itemnumber>
<itemnumber>
<type>Smartphone</type>
<make>Samsung</make>
<price>10000.0</price>
<model>Galaxy A5</model>
<id>S00001</id>
</itemnumber></root>`;
var parser = new DOMParser();
return parser.parseFromString(xmlString, "text/xml");
}
<html>
<button type="button" onclick="loadDoc()">Smartphones</button>
<table id="dem"></table>
</html>