0

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?

Mohammad Areeb Siddiqui
  • 9,795
  • 14
  • 71
  • 113
  • I don't get what the question is. Can you elaborate? How did you check the DOM doesn't have the class? – putvande Jun 19 '14 at 14:19
  • Pay attention: IE don't show you most of the DOM manipulations done. It give just the DOM sended by the server. – Nicolas Henrard Jun 19 '14 at 14:20
  • @putvande I am trying to add a class to the images of the `html` response returned from an AJAX call. When I log it into the console, it shows me a class has been added but the DOM doesn't have that class on the images. Why? – Mohammad Areeb Siddiqui Jun 19 '14 at 14:21
  • because you add class to jsonObj. And I don't see that you add your jsonObj to the DOM – Dmitry Jun 19 '14 at 14:21

2 Answers2

1

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);
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
1

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;
drinchev
  • 19,201
  • 4
  • 67
  • 93