18

The following code gets a value from an Ajax json call and should append it to a div with the corresponding value. Thing is, it appends as text, not as html, so I literally see my html as text on the page. How can I fix this?

$.ajax({
    url: "https://domain.com/maprequest.php",
    type: "POST",
    dataType: 'json',
    data: JSON.stringify(url_array),
    crossDomain: true,
    success: function(response) {
        $.each(response, function(k, v) {
            if (v != "") {
                $('.offer-list li .img a')[k].append("<div class='hoverbox'><img src='" + v + "' alt='hover' /></div>");
            }
        });
    }
});
Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93
Hans Wassink
  • 2,529
  • 3
  • 30
  • 45

1 Answers1

28

By writing $('.offer-list li .img a')[k] you get the actual HTML element at index k, not a jQuery set. I guess your problem is caused by this.

Try this code.

$('.offer-list li .img a').eq(k).append("<div class='hoverbox'><img src='" + v + "' alt='hover' /></div>");

The eq function will internally filter the jQuery set for the HTML element at index k. See the documentation here.

What actually confused you is that a HTML element has the append and appendChild methods, and each respectively appends pure text, or a child node to a given element, hence your code appended the HTML as pure text.

Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93