2

Using jQuery I'm trying to output Json data containing a big chunk of HTML. This results in the HTML is being printed out in plain text, because it puts quotations marks around it. I want it as formated HTML. How can I achieve this? It's Json data from the Reddit API.

My jQuery

    $.getJSON('https://www.reddit.com/r/GlobalOffensive/.json', function(data) {

    $.each(data.data.children.slice(0,5), function(key, val) {

        longHTML += '<div class="post">'+val.data.selftext_html+'</div><hr>'

    });

      $(".reddit-content").html(longHTML);

});

Results in

<div class="post">"<!-- SC_OFF --><div class="md"><h3><a href="#fnatic-logo"></a> Fnatic 0-2 <a href="#vp-logo"> ... etc etc ... <hr/> </div><!-- SC_ON -->"</div>
Lehar001
  • 73
  • 11
  • The problem is that the API is returning HTML with all the special characters replaced with their entities. So they get displayed literally. I'm not sure why they're doing that. – Barmar Sep 11 '15 at 23:31
  • 1
    From the reddit [API documentation](https://github.com/reddit/reddit/wiki/JSON): NOTE: The HTML string will be escaped. You must unescape to get the raw HTML. – Barmar Sep 11 '15 at 23:33
  • 1
    $.getJSON('https://www.reddit.com/r/GlobalOffensive/.json', function(data) { var longHTML = ""; $.each(data.data.children.slice(0,5), function(key, val) { var temp = $.parseHTML(val.data.selftext_html); if(temp){ longHTML += '
    ' + $(temp).text() + '

    '; }else{ longHTML += '
    '+temp+'

    ' } }); $(".reddit-content").html(longHTML); }); See this fiddle: http://jsfiddle.net/hexjrbcb/
    – Gregg Duncan Sep 11 '15 at 23:42

1 Answers1

0

This is easy:

$(".reddit-content").html($(longHTML));

By passing HTML code into jQuery() it creates the corresponding DOM out of it.

wiesion
  • 2,349
  • 12
  • 21