I'm trying to build a page with AJAX and JavaScript that displays the contents of an XML file filtering it by node value. The XML is similar to this:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
</cd>
<cd>
<title>Hide your heart</title>
<artist>Bonnie Tyler</artist>
<country>UK</country>
</cd>
<cd>
<title>Greatest Hits</title>
<artist>Dolly Parton</artist>
<country>USA</country>
</cd>
<cd>
<title>Still got the blues</title>
<artist>Gary Moore</artist>
<country>UK</country>
</cd>
</catalog>
After the XMLHttpRequest, the CD data are converted to an array (nodeList) before being displayed in a table:
function handleXML (xmlData) {
var data = xmlData;
var cd = data.getElementsByTagName("cd");
var arrayCD = Array.prototype.slice.call(cd);
var table = "<table>";
table += "<tbody>";
for ( var i = 0, len = arrayCD.length; i < len; i++ ) {
table += "<tr>";
table += "<td>"+ arrayCD[i].getElementsByTagName("title")[0].firstChild.nodeValue +"</td>";
table += "<td>"+ arrayCD[i].getElementsByTagName("artist")[0].firstChild.nodeValue +"</td>";
table += "<td>"+ arrayCD[i].getElementsByTagName("country")[0].firstChild.nodeValue +"</td>";
table += "</tr>";
}
table += "</tbody>";
table += "</table>";
return table;
}
My question is how to filter the table data so that (for instance) only CDs produced in the UK are displayed. I've been struggling with this for a while and now begin to feel more and more confused. I suppose a solution could be something like:
arrayCD.filter(function(c) {
var filterC = c.getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue;
return (filterC = "UK");
});
(which should be inserted between var arrayCD and var table). But I simply can't make it work. I'd be glad if somebody could suggest an answer.
data-attrto each node (td in your table) and setstyle=display:nonein your loop.$('[data-country="blah"]').each(el => $(el).style('display', 'none'))or something like that, cant remember jquery api anymoredocument.querySelectoranyway...the strategy is basically the same