Reputation: 277
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. Now, 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?
Upvotes: 1
Views: 1157
Reputation: 1138
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
}).appendTo($div);
And change your JSON data structure to the following:
[{
"posterPath" : "imgsMovie/MovieName/poster.jpg"
}]
Upvotes: 4
Reputation: 1411
$(".rightposter").append(data[i].poasterPath)
change to
$(".rightposter").append($(data[i].poasterPath).addClass("your class"));
$(".rightposter").append($("<img src=http://lorempixel.com/output/sports-q-c-130-67-5.jpg>").addClass("red"));
.red { border:3px solid red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='rightposter'></div>
Upvotes: 2
Reputation: 56
if this is the only img tag in code then you can write $('img').addClass('your class') or $('.rightposter img').addClass('your class');
Upvotes: 1
Reputation: 39322
You can use jQuery's .find()
method to get image and add class on it.
$(".rightposter").append(data[i].posterPath).find("img").addClass("myClass");
Upvotes: 0