Hans Wassink Hans Wassink - 29 days ago 12
HTML Question

jQuery appends as text instead of html

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>");
}
});
}
});

Answer

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.

Comments