Note that there are some explanatory texts on larger screens.

plurals
  1. PORead XML File with JQuery and Write XML Attributes to Series of HTML Elements on a Webpage
    text
    copied!<p>I have an image slider on a page that reads an XML file called "slider.xml" that kinda looks like this:</p> <pre><code>&lt;slider&gt; &lt;slide&gt; &lt;link&gt;http://www.example.com/1&lt;/link&gt; &lt;path&gt;http://image.jpg&lt;/path&gt; &lt;/slide&gt; &lt;/slider&gt; </code></pre> <p>There's multiple "slide" elements but I didn't include them for space reasons. I have some HTML that looks like this:</p> <pre><code>&lt;body&gt; &lt;div class="slide"&gt;&lt;/div&gt; &lt;div class="slide"&gt;&lt;/div&gt; &lt;div class="slide"&gt;&lt;/div&gt; &lt;div class="slide"&gt;&lt;/div&gt; &lt;div class="slide"&gt;&lt;/div&gt; &lt;/body&gt; </code></pre> <p>I want to read this XML file and write the "link" attribute to the "div" elements on an HTML page as a title attribute. I want it to look like this:</p> <pre><code>&lt;body&gt; &lt;div class="slide" title="http://www.example.com/1"&gt;&lt;/div&gt; &lt;div class="slide" title="http://www.example.com/2"&gt;&lt;/div&gt; &lt;div class="slide" title="http://www.example.com/3"&gt;&lt;/div&gt; &lt;div class="slide" title="http://www.example.com/4"&gt;&lt;/div&gt; &lt;div class="slide" title="http://www.example.com/5"&gt;&lt;/div&gt; &lt;/body&gt; </code></pre> <p>So far I have tried this but haven't had any luck:</p> <pre><code>$(document).ready(function () { $.ajax({ type: "GET", url: "slider.xml", dataType: "xml", success: function(xml) { $(xml).find('slide').each(function(){ var url = $(this).find('link').text(); $('.slide').attr('title', url); }); } }); }); </code></pre> <p>I don't have issues reading the XML file, but run into problems after I parse the XML attributes and attach it to the various divs. Should I create a loop and store the xml attributes in an array? Is there a better way to do this? </p> <p>Also, I cannot edit the XML or HTML. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload