In this article I will show you how to use jQuery add image using XML file. Here, First, you add a source or URL of an image to an XML document, and then by using jQuery ajax we can gather details of each image. Once, you extract image details from the source to an <img> tag using jQuery. By using jQuery “.attr()” method you will get the properties of the image then, using “.appendTo()” append method in jQuery add or append the image to an HTML DIV element.
XML File:
Create an XML file and name it as imageList.xml. Copy and paste the following code.
<?xml version="1.0" encoding="utf-8" ?>
<list>
<ref>
<img>images/f1.jpg</img>
<title>AngularJS for Beginners</title>
<alt>Beginners Guide</alt>
</ref>
<ref>
<img>images/f2.jpg</img>
<title>XML for Beginners</title>
<alt>Beginners Guide</alt>
</ref>
<ref>
<img>images/f3.jpg</img>
<title>HTML5 Xpressions</title>
<alt>HTML5 Tips</alt>
</ref>
</list>
HTML File:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'imageList.xml',
dataType: 'xml',
success: function (xml) {
$(xml).find('ref').each(function () {
img = $(this).find('img').text();
title = $(this).find('title').text();
alt = $(this).find('alt').text();
$('<img />')
.attr('src', "" + img + "") // ADD IMAGE PROPERTIES.
.attr('title', title)
.attr('alt', alt)
.width('113px').height('113px')
.css('border', "solid 1px green")
.appendTo($('#show_images')); // ADD THE IMAGE TO DIV.
});
}
});
});
</script>
<body>
<div id="show_images" style="width:auto;"></div>
</body>
Output- appendto in jQuery:
Post your comments / questions
Recent Article
- How to fix HAXM is not installed |in Android Studio
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
- Unicode error 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
- Could not find the 'angular-devkit/build-angular:dev-server' builder's node package | Angular Error
Related Article