Im trying to grab the channel display name and channel id from some XML data but it cant seem to get it to work. For each channel display name I what to grab the channel display name and channel id, this is what I have tried, it grabs the data but it puts them all into one string and I want them on separate lines.
var xml = "<tv generator-info-name='tvchannels' source-info-name='tvchannels'><channel id='1234'><display-name>Channel 1</display-name></channel><channel id='5678'><display-name>Channel 2</display-name></channel><channel id='543553'><display-name>Channel 3</display-name></channel><channel id='324324'><display-name>Channel 4</display-name></channel></tv>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$xml.find("display-name").each(
function (i,e) {
$('#title').append($xml.find("display-name"));
$('#channelid').append($xml.find("channel").attr("id"));
});
XPATH and XSL/XSLT do this, however they can be difficult to learn/use compared to javascript/JSON. JavaScript Object Notation, JSON, is preferred. Have a look at
XPath Examples from Microsoft
Introduction to using XPath in JavaScript from MDN.
Iterator Example
var iterator = document.evaluate('//phoneNumber', documentNode, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null );
try {
var thisNode = iterator.iterateNext();
while (thisNode) {
alert( thisNode.textContent );
thisNode = iterator.iterateNext();
}
}
catch (e) {
alert( 'Error: Document tree modified during iteration ' + e );
}
When you're looping through $xml, you need to use $(this) or the second argument passed to .each() in order to access the individual channels as you're looping through. See the code below:
var xml = "<tv generator-info-name='tvchannels' source-info-name='tvchannels'><channel id='1234'><display-name>Channel 1</display-name></channel><channel id='5678'><display-name>Channel 2</display-name></channel><channel id='543553'><display-name>Channel 3</display-name></channel><channel id='324324'><display-name>Channel 4</display-name></channel></tv>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$xml.find('channel').each(function (i,e) {
$('#title').append($(this).find("display-name"));
$('#title').append($('<br />'));
$('#channelid').append($(this).attr("id"));
$('#channelid').append($('<br />'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Titles: <br />
<div id="title"></div><br />
Channel IDs: <br />
<div id="channelid"></div>
You are not using the results of the find method. I believe you need smth like
var xml = "<tv generator-info-name='tvchannels' source-info-name='tvchannels'><channel id='1234'><display-name>Channel 1</display-name></channel><channel id='5678'><display-name>Channel 2</display-name></channel><channel id='543553'><display-name>Channel 3</display-name></channel><channel id='324324'><display-name>Channel 4</display-name></channel></tv>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$xml.find("channel").each(function(index, e) {
$('#title').append($(e).find("display-name").text() + '<br />');
$('#channelid').append(e.getAttribute("id") + '<br />');
});
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div id="title"></div>
<div id="channelid"></div>
Related
I'm trying to setup a form to allow people modifying some parts of XML files, using standard inputs/textareas/checkboxes, etc; and see the corresponding XML file modified in "real time", in their browser (so using JS)
What I have been doing so far is have an attribute on each form element that stores an XPath to see which XML node/text the input corresponds to.
I can get the xpath value from the XML, but them I'm unable to modify the corresponding XML.
Here is the code :
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function updateXml(input) {
newvalue = $(input).val();
xmlStr = $("#xml" ).val();
if(xmlStr=="" ) return;
xmlObj = $.parseXML(xmlStr);
xpath = $(input).attr('data-xpath');
result = xmlObj.evaluate(xpath, xmlObj, null, XPathResult.ANY_TYPE, null);
element = result.iterateNext();
//element is a copy of the noden I can't modify it directly, it won't be reflected in xmlObj...
//this will work in my example, but it's too "hardcoded", I want to change that using xpath
xmlObj.getElementsByTagName("person" )[0].getElementsByTagName("name" )[0].innerHTML = newvalue;
var xmlText = new XMLSerializer().serializeToString(xmlObj);
$("#xml" ).val(xmlText);
}
</script>
<form>
<input onkeyup="updateXml(this);" data-xpath="/person/name" />
<textarea id="xml" style="width: 800px;height: 600px;">
<?xml version="1.0" encoding="ISO-8859-1"?>
<person>
<name>Paul</name>
<age>12</age>
</person>
</textarea>
</form>
In other words, I would like to be able to change the "age" using another input field, without changing the code...
Any idea how I can do this ? or another (simple) way of doing it ?
Thanks !
Your basic idea is correct: manipulate the document using the XML DOM elements, then serialize back and update the textarea.
The sample code below is still incomplete and needs some polishment before it can go to production. However, I think I have added a lot of useful code and demonstrated how it can be done!
function getElementsByXPath(xpath, elt, val)
{
var results = [];
var nsResolver = document.createNSResolver( elt.ownerDocument == null ? elt.documentElement : elt.ownerDocument.documentElement );
var xPathRes = document.evaluate(xpath, elt, nsResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < xPathRes.snapshotLength; i++) {
var element = xPathRes.snapshotItem (i);
if (element instanceof Attr) { results.push(val); }//element.nodeValue);
else if (element instanceof Element && element.outerHTML) { element.innerHTML = val;
results.push(element.outerHTML);}
else results.push(element); //TODO
}
return results;
}
function updateXml(input) {
newvalue = $(input).val();
xmlStr = $("#xml" ).val();
if(xmlStr=="" ) return;
var xml = (new DOMParser()).parseFromString(xmlStr, "text/xml");
var xpath = $(input).attr('data-xpath');
var results = getElementsByXPath(xpath, xml, newvalue);
/*var ResultTxt = '';
results.forEach(function(result) {
ResultTxt += result + "\n";
});
$("#result" ).val(ResultTxt);
console.log(ResultTxt);*/
var xmlText = new XMLSerializer().serializeToString(xml);
$("#xml" ).val(xmlText);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<form>
<input onkeyup="updateXml(this);" data-xpath="/person/name" />
<textarea id="xml" style="width: 800px;height: 200px;">
<?xml version="1.0" encoding="ISO-8859-1"?>
<person>
<name>Paul</name>
<age>12</age>
</person>
</textarea>
</form>
</body>
</html>
I am new to jQuery, and js for that matter. I am trying to create a table from XML data, but I can't get the output correct. Here is what I have so far:
HTML:
<table id="daily_fruit">
<tbody>
</tbody>
</table>
jQuery:
var xml = '<daily_fruit><day>Mon</day><type>apple</type><day>Tues</day><type>orange</type><day>Wed</day><type>banana</type><day>Thur</day><type>pear</type></daily_fruit>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$($xml).each(function() {
var showTimes = $xml.find('daily_fruit').each(function() {
var $day = $(this).find('day').text();
var $type = $(this).find("type").text();
$("#daily_fruit").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($day))
)
.append($('<td>')
.append($type))
});
});
Current Output:
MonTuesWedThur
appleorangebananapear
Desired Output:
Mon apple
Tues orange
Wed banana
Thur pear
I think I am close, but I just can't figure it out.
Try modifying your XML so that each fruit is within its own tag. Then instead of finding the "daily_fruit" tag for your each loop, use the "fruit" tag.
Here's a jsfiddle:
https://jsfiddle.net/57wgab88/
var xml = '<daily_fruit><fruit><day>Mon</day><type>apple</type></fruit><fruit><day>Tues</day><type>orange</type></fruit><fruit><day>Wed</day><type>banana</type></fruit><fruit><day>Thur</day><type>pear</type></fruit></daily_fruit>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$($xml).each(function() {
var showTimes = $xml.find('fruit').each(function() {
var $day = $(this).find('day').text();
var $type = $(this).find("type").text();
$("#daily_fruit").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($day))
.append($('<td>')
.append($type))
)
});
});
Given such XML structure, you're supposed to iterate through <day> elements instead. Assuming that each <day> is always followed by corresponding <type> element :
var xml = '<daily_fruit><day>Mon</day><type>apple</type><day>Tues</day><type>orange</type><day>Wed</day><type>banana</type><day>Thur</day><type>pear</type></daily_fruit>';
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$($xml).each(function() {
var showTimes = $xml.find('day').each(function() {
var $day = $(this).text();
var $type = $(this).next("type").text();
$("#daily_fruit").find('tbody')
.append($('<tr>')
.append($('<td>')
.append($day))
.append($('<td>')
.append($type))
)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="daily_fruit">
<tbody>
</tbody>
</table>
I'd like to save the html string of the DOM, and later restore it to be exactly the same. The code looks something like this:
var stringified = document.documentElement.innerHTML
// later, after serializing and deserializing
document.documentElement.innerHTML = stringified
This works when everything is perfect, but when the DOM is not w3c-comliant, there's a problem. The first line works fine, stringified matches the DOM exactly. But when I restore from the (non-w3c-compliant) stringified, the browser does some magic and the resulting DOM is not the same as it was originally.
For example, if my original DOM looks like
<p><div></div></p>
then the final DOM will look like
<p></p><div></div><p></p>
since div elements are not allowed to be inside p elements. Is there some way I can get the browser to use the same html parsing that it does on page load and accept broken html as-is?
Why is the html broken in the first place? The DOM is not controlled by me.
Here's a jsfiddle to show the behavior http://jsfiddle.net/b2x7rnfm/5/. Open your console.
<body>
<div id="asdf"><p id="outer"></p></div>
<script type="text/javascript">
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
document.getElementById('outer').appendChild(insert);
var e = document.getElementById('asdf')
console.log(e.innerHTML);
e.innerHTML = e.innerHTML;
console.log(e.innerHTML); // This is different than 2 lines above!!
</script>
</body>
If you need to be able to save and restore an invalid HTML structure, you could do it by way of XML. The code which follows comes from this fiddle.
To save, you create a new XML document to which you add the nodes you want to serialize:
var asdf = document.getElementById("asdf");
var outer = document.getElementById("outer");
var add = document.getElementById("add");
var save = document.getElementById("save");
var restore = document.getElementById("restore");
var saved = undefined;
save.addEventListener("click", function () {
if (saved !== undefined)
return; /// Do not overwrite
// Create a fake document with a single top-level element, as
// required by XML.
var parser = new DOMParser();
var doc = parser.parseFromString("<top/>", "text/xml");
// We could skip the cloning and just move the nodes to the XML
// document. This would have the effect of saving and removing
// at the same time but I wanted to show what saving while
// preserving the data would look like
var clone = asdf.cloneNode(true);
var top = doc.firstChild;
var child = asdf.firstChild;
while (child) {
top.appendChild(child);
child = asdf.firstChild;
}
saved = top.innerHTML;
console.log("saved as: ", saved);
// Perform the removal here.
asdf.innerHTML = "";
});
To restore, you create an XML document to deserialize what you saved and then add the nodes to your document:
restore.addEventListener("click", function () {
if (saved === undefined)
return; // Don't restore undefined data!
// We parse the XML we saved.
var parser = new DOMParser();
var doc = parser.parseFromString("<top>" + saved + "</top>", "text/xml");
var top = doc.firstChild;
var child = top.firstChild;
while (child) {
asdf.appendChild(child);
// Remove the extra junk added by the XML parser.
child.removeAttribute("xmlns");
child = top.firstChild;
}
saved = undefined;
console.log("inner html after restore", asdf.innerHTML);
});
Using the fiddle, you can:
Press the "Add LadyGaga..." button to create the invalid HTML.
Press "Save and Remove from Document" to save the structure in asdf and clear its contents. This prints to the console what was saved.
Press "Restore" to restore the structure that was saved.
The code above aims to be general. It would be possible to simplify the code if some assumptions can be made about the HTML structure to be saved. For instance blah is not a well-formed XML document because you need a single top element in XML. So the code above takes pains to add a top-level element (top) to prevent this problem. It is also generally not possible to just parse an HTML serialization as XML so the save operation serializes to XML.
This is a proof-of-concept more than anything. There could be side-effects from moving nodes created in an HTML document to an XML document or the other way around that I have not anticipated. I've run the code above on Chrome and FF. I don't have IE at hand to run it there.
This won't work for your most recent clarification, that you must have a string copy. Leaving it, though, for others who may have more flexibility.
Since using the DOM seems to allow you to preserve, to some degree, the invalid structure, and using innerHTML involves reparsing with (as you've observed) side-effects, we have to look at not using innerHTML:
You can clone the original, and then swap in the clone:
var e = document.getElementById('asdf')
snippet.log("1: " + e.innerHTML);
var clone = e.cloneNode(true);
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
document.getElementById('outer').appendChild(insert);
snippet.log("2: " + e.innerHTML);
e.parentNode.replaceChild(clone, e);
e = clone;
snippet.log("3: " + e.innerHTML);
Live Example:
var e = document.getElementById('asdf')
snippet.log("1: " + e.innerHTML);
var clone = e.cloneNode(true);
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
document.getElementById('outer').appendChild(insert);
snippet.log("2: " + e.innerHTML);
e.parentNode.replaceChild(clone, e);
e = clone;
snippet.log("3: " + e.innerHTML);
<div id="asdf">
<p id="outer">
<div>ladygaga</div>
</p>
</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Note that just like the innerHTML solution, this will wipe out event handlers on the elements in question. You could preserve handlers on the outermost element by creating a document fragment and cloning its children into it, but that would still lose handlers on the children.
This earlier solution won't apply to you, but may apply to others in the future:
My earlier solution was to track what you changed, and undo the changes one-by-one. So in your example, that means removing the insert element:
var e = document.getElementById('asdf')
console.log("1: " + e.innerHTML);
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
var outer = document.getElementById('outer');
outer.appendChild(insert);
console.log("2: " + e.innerHTML);
outer.removeChild(insert);
console.log("3: " + e.innerHTML);
var e = document.getElementById('asdf')
snippet.log("1: " + e.innerHTML);
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
var outer = document.getElementById('outer');
outer.appendChild(insert);
snippet.log("2: " + e.innerHTML);
outer.removeChild(insert);
snippet.log("3: " + e.innerHTML);
<div id="asdf">
<p id="outer">
<div>ladygaga</div>
</p>
</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Try utilizing Blob , URL.createObjectURL to export html ; include script tag in exported html which removes <div></div><p></p> elements from rendered html document
html
<body>
<div id="asdf">
<p id="outer"></p>
</div>
<script>
var insert = document.createElement("div");
var text = document.createTextNode("ladygaga");
insert.appendChild(text);
document.getElementById("outer").appendChild(insert);
var elem = document.getElementById("asdf");
var r = document.querySelectorAll("[id=outer] ~ *");
// remove last `div` , `p` elements from `#asdf`
for (var i = 0; i < r.length; ++i) {
elem.removeChild(r[i])
}
</script>
</body>
js
var e = document.getElementById("asdf");
var html = e.outerHTML;
console.log(document.body.outerHTML);
var blob = new Blob([document.body.outerHTML], {
type: "text/html"
});
var objUrl = window.URL.createObjectURL(blob);
var popup = window.open(objUrl, "popup", "width=300, height=200");
jsfiddle http://jsfiddle.net/b2x7rnfm/11/
see this example: http://jsfiddle.net/kevalbhatt18/1Lcgaprc/
MDN cloneNode
var e = document.getElementById('asdf')
console.log(e.innerHTML);
backupElem = e.cloneNode(true);
// Your tinkering with the original
e.parentNode.replaceChild(backupElem, e);
console.log(e.innerHTML);
You can not expect HTML to be parsed as a non-compliant HTML. But since the structure of compiled non-compliant HTML is very predictable you can make a function which makes the HTML non-compliant again like this:
function ruinTheHtml() {
var allElements = document.body.getElementsByTagName( "*" ),
next,
afterNext;
Array.prototype.map.call( allElements,function( el,i ){
if( el.tagName !== 'SCRIPT' && el.tagName !== 'STYLE' ) {
if(el.textContent === '') {
next = el.nextSibling;
afterNext = next.nextSibling;
if( afterNext.textContent === '' ) {
el.parentNode.removeChild( afterNext );
el.appendChild( next );
}
}
}
});
}
See the fiddle:
http://jsfiddle.net/pqah8e25/3/
You have to clone the node instead of copying html. Parsing rules will force the browser to close p when seeing div.
If you really need to get html from that string and it is valid xml, then you can use following code ($ is jQuery):
var html = "<p><div></div></p>";
var div = document.createElement("div");
var xml = $.parseXML(html);
div.appendChild(xml.documentElement);
div.innerHTML === html // true
You can use outerHTML, it perseveres the original structure:
(based on your original sample)
<div id="asdf"><p id="outer"></p></div>
<script type="text/javascript">
var insert = document.createElement('div');
var text = document.createTextNode('ladygaga');
insert.appendChild(text);
document.getElementById('outer').appendChild(insert);
var e = document.getElementById('asdf')
console.log(e.outerHTML);
e.outerHTML = e.outerHTML;
console.log(e.outerHTML);
</script>
Demo: http://jsfiddle.net/b2x7rnfm/7
I am creating an app in which I have used jQuery mobile autocomplete the listview data is created dynamically from the database the autocomplete listview code is return in the js file. I am able to select the data from the listview and show it in the input field of the autocomplete and then disable the search list.
Know what I want is seens I am get the data from the data base when user select the list data it will display the name but when it click on the save button it should save the id of that name instead of the name in jQuery ui autocomplete its easy because there we can use array with label and value.
But I don't know how to do it in jQuery mobile.
The code for creating the autocomplete in here:
var db = window.openDatabase("Database", "1.0","BPS CRM", 200000);
$( document ).on( "pageinit", "#myPage", function() {
var usrname = new Array();
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
db.transaction(function(tx){
tx.executeSql('select * from users',[],function(tx,results){
var dataset = results.rows;
if(dataset.length > 0){
for(var i = 0; i < dataset.length; i++){
usrname[i] = dataset.item(i).user_name;
}
}
});
});
if ( value && value.length > 1 ) {
for(var j = 0; j < usrname.length; j++){
html += "<li>"+usrname[j]+"</li>";
}
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
$.mobile.activePage.find('input[placeholder="Find a city..."]').attr('id','namesearch');
}
$("ul > li").click(function(){
var textval = $(this).text();
$('#namesearch').val(textval);
$.mobile.activePage.find("[data-role=listview]").children().addClass('ui-screen-hidden');
});
}); });
It will great if small example is given for the same.
Any suggestion is appreciated. Thanks in advance.
I am not exactly sure I understood the question, but I think what your are looking for is to store the user ID in the <li> elements, in addition to having the username as the displayed text.
Something like this might do the job for you:
// declare a collection of Ids where you declare usrname
var usrids = new Array();
// in your execute sql callback, add this line:
usrids.push(dataset.item(i).user_id); // see note below
// in your for loop where you insert li's, modify the line like this :
html +="<li data-userid='" + usrids[j] + "'>"+usrname[j]+"</li>";
// then in your ul>li click event, you can reference your ids like this :
var userId = $(this).data('userid');
Also, as a general note, I think it's better to use usrids.push(...) and usrname.push(...) instead of using usrids[i] = ...; when the element i does not already exist in the given array.
I am developing an app, where on the click of a button, a list of the document information stored in an XML file is shown on screen in a <ul> tag. The current JavaScript in the function is;
function viewXMLFiles() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "TestInfo.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("docname").innerHTML = xmlDoc.getElementsByTagName("document_name")[0].childNodes[0].nodeValue;
document.getElementById("filetype").innerHTML = xmlDoc.getElementsByTagName("file_type")[0].childNodes[0].nodeValue;
document.getElementById("fileloc").innerHTML = pathToRoot + "/" + document.getElementById("docname").innerHTML;
document.getElementById("docname1").innerHTML = xmlDoc.getElementsByTagName("document_name")[1].childNodes[0].nodeValue;
document.getElementById("filetype1").innerHTML = xmlDoc.getElementsByTagName("file_type")[1].childNodes[0].nodeValue;
document.getElementById("fileloc1").innerHTML = pathToRoot + "/" + document.getElementById("docname1").innerHTML;
}
but i want to set it so that even if more file information is added, the function will display it too. i have already looked at Jquery xml parsing loops this question, but i couldn't get the function to work. Here's the XML file;
<document_list>
<document>
<document_name>Holidays.pdf</document_name><br />
<file_type>.pdf</file_type> <br />
<file_location>TEST</file_location> <br />
</document>
<document>
<document_name>iPhone.jsNotes.docx</document_name><br />
<file_type>.docx</file_type><br />
<file_location>TEST</file_location><br />
</document>
</document_list>
And this is the HTML i am using. There's a button and the <ul> tags i'm using;
<button onclick = "viewXMLFiles(); document.getElementById('showDocumentLink').style.display = 'block';">View Document Info</button><br>
<div id = "doclist">
<h2>Document 1;</h2>
<label>Document Name;</label><br><span id = "docname"></span><br>
<label>File Type</label><br><span id = "filetype"></span><br>
<label>File Location</label><br><span id = "fileloc"></span><br>
</div>
<div id = "doclist">
<h2>Document 2;</h2>
<label>Document Name;</label><br><span id = "docname1"></span><br>
<label>File Type</label><br><span id = "filetype1"></span><br>
<label>File Location</label><br><span id = "fileloc1"></span><br>
</div>
Can anyone help me put this into a loop? I have linked jQuery and jQTouch so i can use both of them.
Thank you so much in advance xx
Use following loop code.
<script>
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
var documents = $xml.find('document_list');
documents.children('document').each(function() {
var name = $(this).find('document_name').text();
var file_type = $(this).find('file_type').text();
var file_location = $(this).find('file_location').text();
// now do whatever you like with above variable
});
</script>
Using Irfan's answer as a base, to get the values into your labels add a counter, then just insert the values grabbed from the XML parsing loop into the corresponding span.
<script>
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "TestInfo.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
$xml = $( xmlDoc );
var documents = $xml.find('document_list');
var doccount = 0;
//will be used to find the HTML elements
var namelabel = "docname";
var typelabel = "filetype";
var locationlabel = "fileloc";
documents.children('document').each(function() {
var name = $(this).find('document_name').text();
var file_type = $(this).find('file_type').text();
var file_location = $(this).find('file_location').text();
//after the first document we need to add the number to the span id
if(doccount > 0){
namelabel = "docname" + doccount;
typelabel = "filetype" + doccount;
locationlabel = "fileloc" + doccount;
}
//insert the XML values into the label
$('span#'+namelabel).html(name);
$('span#'+typelabel).html(file_type);
$('span#'+locationlabel).html(file_location);
//increment the counter
doccount++;
});
</script>
Here is a native JavaScript implementation so you can see how you'd do it that way and compare, etc.
function viewXMLFiles() {
// var everything
var xmlhttp = new XMLHttpRequest(),
xmlDoc,
nodes, i, j, counter = -1, suffix,
document_name, file_type, file_location;
// request page
xmlhttp.open("GET", "TestInfo.xml", false),
xmlhttp.send();
// false meant synchronous req. so can go straight to reading document
xmlDoc = xmlhttp.responseXML;
// loop over <document> nodes
nodes = xmlDoc.childNodes; // shorthand
j = nodes.length;
for (i = 0; i < j; ++i) {
if ('document' === nodes[i].tagName.toLowerCase()) {
// nodes[i] is a <document>, increment counter
++counter;
// get nodes of intrest
document_name = nodes[i].getElementsByTagName("document_name")[0];
file_type = nodes[i].getElementsByTagName("file_type")[0];
file_location = nodes[i].getElementsByTagName("file_location")[0];
// do what you want with these, e.g.
suffix = counter || ''; // don't append a number for 0
document.getElementById('docname'+suffix).textContent = document_name.textContent;
document.getElementById('filetype'+suffix).textContent = file_type.textContent;
document.getElementById('fileloc'+suffix).textContent = pathToRoot + "/" + file_location.textContent;
}
}
}
Furthermore, you should consider the validity of your HTML, as I mentioned in my comment;
there should be no spaces around the equals sign of an attribute name/value pair, i.e. <tag attrib="val"/> not <tag attrib = "val"/>
every id attribute should have a unique value, not shared with any other on the document, i.e. not <tag id="shared"/><tag id="shared"/>