Bokchee 88 Bokchee 88 - 1 year ago 76
CSS Question

How to add get image from JSON file, add class and append in div?

I am trying to add a class on image, that i am taking from local JSON file.
my JSON file:

"posterPath" : "<img src = imgsMovie/MovieName/poster.jpg>"


This is my file i am taking from JSON, it is an image tag.
I want in this image to have an class dynamically added with jQuery.

my div is

<div class='rightposter'></div>

And this is how i get my image from JSON

$(".rightposter").append(data[i].posterPath)//this will display my image on my page without class.

How can i add class inside img tag?

Answer Source

This is a cleaner way to insert dynamically constructed HTML tags using jQuery.

Use the following syntax to build your HTML and to append it to the DOM:

$div = $('.rightposter');

$('<img />', {
 'src': data[i].posterPath,
 'class': "myClass" //put your class name here

And change your JSON data structure to the following:

    "posterPath" : "imgsMovie/MovieName/poster.jpg"