Home > other >  Rendering HTML elements from a JSON object get. How to render HTML?
Rendering HTML elements from a JSON object get. How to render HTML?

Time:05-07

Feels good to finally submit some of my own questions here in the pursuit of knowledge. I was wondering if anyone could help me with the following problem. I have a jQuery GET where a JSON object gets pulled via an API.

My code:

var div = document.getElementById('myData');


jQuery(document).ready(function() {
  const Url = 'https://boards-api.greenhouse.io/v1/boards/sunrock/jobs/5104060003';
  jQuery('.btn').click(function() {
    jQuery.ajax({
      url: Url,
      type: 'GET',
      success: function(result) {
        console.log(result);
        x = result.title
        var jobTitle = x;
        document.getElementById('jobTitle').innerHTML = jobTitle;
        y = result.content
        var jobDescription = y;
        document.getElementById('jobDescription').innerHTML = jobDescription;
      },
      error: function(error) {
        console.log(`Error ${error}`)
      },

    });

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button class='btn'>
Clicke here for the GET request
</button>

<div id='jobTitle'>Job Title here</div>
<div id='jobDescription'>Job Description here</div>

I want some of this information to display in HTML. But whenever i apply a variable with the information to a div using innerHTML, i get the following:

<p><strong>Your role</strong></p> <p>

As you can see the HTML elements are typed out fully, which is weird. Does anyone know how to remedy this?

I have a jsFiddle with my code here: https://jsfiddle.net/whimsicalcodingman/38a45udt/159/

CodePudding user response:

As @GrafiCode pointed out, the issue isn't in your code, when you access the content property. The issue is in the information you are receiving for the content property.

The property content returns this: "content": "&lt;p&gt;&lt;strong&gt;Your role&lt;/strong&gt;&lt;/p&gt;\n&lt;p&gt;The Project Finance...

Which is:

"content": "<p><strong>Your role</strong></p>\n<p>The Project Finance...

Therefore, I see two options for you, you can either fix this in the backend or fix this in the frontend.

If you want to fix this in the frontend, then you might be interested to use an HTML Sanitizer.

For example, you could Mozilla's HTML Sanitizer API

If you want to fix this in the backend, you can either fix the text manually or you can try to find a library.

For example, if your backend is NodeJS, then you can use this package library sanitize-html

  • Related