I have an image slider on a page that reads an XML file called “slider.xml” that kinda looks like this:
<slider>
<slide>
<link>http://www.example.com/1</link>
<path>http://image.jpg</path>
</slide>
</slider>
There’s multiple “slide” elements but I didn’t include them for space reasons. I have some HTML that looks like this:
<body>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
</body>
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:
<body>
<div class="slide" title="http://www.example.com/1"></div>
<div class="slide" title="http://www.example.com/2"></div>
<div class="slide" title="http://www.example.com/3"></div>
<div class="slide" title="http://www.example.com/4"></div>
<div class="slide" title="http://www.example.com/5"></div>
</body>
So far I have tried this but haven’t had any luck:
$(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);
});
}
});
});
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?
Also, I cannot edit the XML or HTML.
All your divs will have the same title since you call
$('.slide')which select them all.This should work: