Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>");
            }
        });
    }
});
like image 314
Hans Wassink Avatar asked Nov 07 '16 09:11

Hans Wassink


1 Answers

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.

like image 87
Zoltán Tamási Avatar answered Oct 22 '22 14:10

Zoltán Tamási