Dynamically add Image to a DIV Element using jQuery .appendTo() Method

← PrevNext →

Here is a quick tip on how to bind images dynamically to an HTML DIV element using jQuery. I have received mails from many of my visitors who were desperately looking for a quick solution on how to extract images from remote folders using jQuery. Let me first clear this to you that you cannot directly extract images or files from a server folder using JavaScript or jQuery.

However, here is a simple work around and I hope it will be useful. I will first add the source (or URL) of each image to an XML document, assigning a node each for the images. Then, extract details of each image from the document using Ajax. Once, I have extracted the image source or other details, I’ll assign the source to an <img /> tag, dynamically, using jQuery.

Using jQuery “.attr()” method, I’ll add the source and properties to all the images. Finally, I’ll add or append the image to an HTML DIV element using jQuery “.appendTo()” method.

Let’s see the example.

First, we will create an XML document and add the source of each image and some miscellaneous properties to it.

The XML
<?xml version="1.0"?>
<!--   Last edited by https://www.encodedna.com   -->
<list>
  <ref>
    <image>angularjs.png</image>
    <title>AngularJS for Beginners</title>
    <alt>Beginners Guide</alt>
  </ref>
  <ref>
    <image>xml.png</image>
    <title>XML for Beginners</title>
    <alt>Beginners Guide</alt>
  </ref>
  <ref>
    <image>html5.png</image>
    <title>HTML5 Xpressions</title>
    <alt>HTML5 Tips</alt>
  </ref>
</list>

The child nodes <image> have URL for each image in the root folder. However, you may add a folder name, if the images are inside another folder. For example

<image>FolderName/angularjs.png</image>

The Markup and the Script

The markup for this example is simple. Inside the <body> tag of the page, I have included the DIV element and assigned an ID to it.

<html>
<head>
    <title>Dynamically add Image to a DIV Element using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>

<body>
    <div id="show_images" style="width:auto;"></div>
</body>

<script>
    $(document).ready(function () {

        $.ajax({
            type: 'GET',
            url: 'https://www.encodedna.com/library/images-source.xml',
            dataType: 'xml',
            success: function (xml) {

                $(xml).find('ref').each(function () {

                    img = $(this).find('image').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')

                        .appendTo($('#show_images'));       // ADD THE IMAGE TO DIV.
                });
            }
        });
    });
</script>
</html>
Try it

You will see an output like this one!

Dynamically add Image using jQuery .appendTo() Method

Additionally, you can add a text below the images along with its properties. Just before concluding this article, I took a glance at another article, which I have previously written about Extracting and Displaying Images from a folder using Asp.Net and adding a text below the images . I took a cue from that article, and decided to add another line to the above code. It might be useful.

Add Text below an Image using jQuery .append() Method

In the XML document, I have the title node, which I am extracting using Ajax in the example. I’ll append or add the title below each image using jQuery “.append()” method. You can add any other text.

$('#show_images').append('<p style="margin:10px 0;font-style:italic;color:#333;">' + 
    title + '</p>');

Add the above line of code below “.appendTo()” method in the script. Moreover, this is how it should be inside the script.

$(xml).find('ref').each(function () {

    img = $(this).find('image').text();
    title = $(this).find('title').text();
    alt = $(this).find('alt').text();

    $('<img />')
        ...
            ...

    // THE jQUERY .append() METHOD.
    $('#show_images').append('<p style="margin:10px 0;font-style:italic;color:#333;">' + 
        title + '</p>');
});

Related: How to Add Text Dynamically to a DIV Element using jQuery

Conclusion

It was a good tip on jQuery. We learned how to extract little details (crucial) from an XML document using jQuery. In addition, we have learned the use of jQuery .attr(), .appendTo() and .append() methods. Finally, we saw how to append an image dynamically to a web page. These are useful methods, and you can add any number of elements dynamically to any web page in your application.

Also Read: How to Extract Data from an XML File Using JavaScript

Thanks for reading .

← PreviousNext →


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.
Delivered by FeedBurner