Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10179

Adding a class to images of a dynamically loaded content

I am loading a content dynamically. The content is in html form and I need to get all of it's images and add a class to them. This is what I have done:

var jsonObj = JSON.parse(http_request.responseText);
console.log($(jsonObj.content).find("img").addClass("img-responsive"));
document.getElementById("myModalContent").innerHTML = jsonObj.content;

The console shows me that a class has been added but the DOM doesn't have that class. Why is it happening?

Upvotes: 0

Views: 246

Answers (2)

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

You don't capture the jQuery object.

You should do something like this :

var jsonObj = JSON.parse(http_request.responseText);
var $Obj = $(jsonObj.content).find("img").addClass("img-responsive").end();
document.getElementById("myModalContent").innerHTML = $Obj[0].outerHTML;

Upvotes: 1

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

Your code is actually creating a new object, add the classes and then, change the innerHTML with the old string. You should change it for the new object html :

var jsonObj = JSON.parse(http_request.responseText);
var $el = $(jsonObj.content).find("img").addClass("img-responsive").end();
document.getElementById("myModalContent").innerHTML = $el.prop('outerHTML');

Or even better :

var jsonObj = JSON.parse(http_request.responseText);
var $el = $(jsonObj.content).find("img").addClass("img-responsive").end();
$("#myModalContent").append($el);

Upvotes: 1

Related Questions