Creating a Dynamic Image Gallery

var img = $("<img></img>"); img.attr("src", "images/newImage.jpg"); $("div").append(img);

Images are becoming a mainstay in web pages. They deliver much more content, and they accomplish it more quickly and often more accurately than text. jQuery and JavaScript allow you to add images to a web page dynamically on demand by creating image elements, then setting the source attribute of each and then appending them to the correct location.

For example, the following code creates an <img> element, sets the src attribute to define the file location, and then appends the image to a <div> element:

var img = $("<img></img>"); img.attr("src", "images/newImage.jpg"); ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.