When updating the HTML content, JavaScript is outputting the code as text instead of running it

I am encountering an issue with adding the body content of a JSON file, which contains HTML code, to my existing HTML. Instead of executing the code, it appears as text within paragraph or header elements. I have searched through various discussions but have been unable to find a solution. Could someone please assist me in identifying what mistake I may be making?

<div id="title">

</div>


<div id="body">

</div>

<script>
  var requestURL = 'https://secure.toronto.ca/cc_sr_v1/data/swm_waste_wizard_APR?limit=1000';
  var request = new XMLHttpRequest();
  request.open('GET', requestURL);
  request.responseType = 'json';
  request.send();
  request.onload = function() {
    var data = request.response;
    document.getElementById("title").innerHTML = data[0].title;
    document.getElementById("body").innerHTML = data[0].body;
  }
</script>

Answer №1

To convert a string with HTML entities into a string of HTML that can be rendered as a DOM element, you can utilize the DOMParser.

document.getElementById("body").innerHTML = htmlDecode("&lt;ul&gt; \n &lt;li&gt;Place item in the &lt;strong&gt;Garbage Bin.&lt;/strong&gt;&lt;/li&gt; \n&lt;/ul&gt;");

function htmlDecode(input) {
  var doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent;
}
<div id="body"></div>

You can implement this method as shown below:

<div id="title"></div>
<div id="body"></div>

<script>

  function htmlDecode(input) {
    var doc = new DOMParser().parseFromString(input, "text/html");
    return doc.documentElement.textContent;
  }

  var requestURL = 'https://secure.toronto.ca/cc_sr_v1/data/swm_waste_wizard_APR?limit=1000';
  var request = new XMLHttpRequest();
  request.open('GET', requestURL);
  request.responseType = 'json';
  request.send();
  request.onload = function() {
    var data = request.response;
    document.getElementById("title").innerHTML = htmlDecode(data[0].title);
    document.getElementById("body").innerHTML = htmlDecode(data[0].body);
  }
</script>

Acknowledgment to this source for introducing DOMParser.

Answer №2

I recently utilized jQuery's "unescape" function, which can be found at this link

The unescape() method generates a new string by replacing hexadecimal escape sequences with their corresponding characters. These escape sequences are commonly generated by functions like escape. It is typically recommended to use decodeURI or decodeURIComponent instead of unescape.

Feel free to give this a try, I hope it proves useful. Thank you

In my recent project, I came across the following JavaScript code snippet:
var requestURL = 'https://secure.toronto.ca/cc_sr_v1/data/swm_waste_wizard_APR?limit=1000';
  var request = new XMLHttpRequest();
  request.open('GET', requestURL);
  request.responseType = 'json';
  request.send();
  request.onload = function() {
    var data = request.response;
    var title_ = $("<p/>").html(data[0].title).text(); 
    var body_ = $("<p/>").html(data[0].body).text(); 
    //$('#body').append($.parseHTML(unescape(data[0].body)));
    $('#title').append(title_);
    $('#body').append(body_);
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="title">

</div>

<div id="body">

</div>

Remember to insert/prepend the data[i] to the elements, rather than setting the value directly (like ht)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can markers be positioned on top of scroll bars?

Looking for a way to display small markers on the scrollbar of an overflow: scroll element, similar to features found in IDEs and text editors like this one: https://github.com/surdu/scroll-marker. I've considered using a pointer-events: none overlay ...

Guide to creating a toggle button

Can someone help me create a button that toggles between displaying block and display none when clicked? I've been trying to use Classlist.toggle with JavaScript, but I'm not sure if I have the correct classes targeted. let showCart = documen ...

Resolving "Module not found: Error: Can't resolve 'url'" issue in Angular 14 while invoking web3 smart contract function

How do I resolve the web3-related errors in my Angular 14 dapp? I attempted to fix the issue by running npm i crypto, npm i http, and more. Every time I try to call a function from a smart contract with code like this.manager = await report.methods.mana ...

Is it possible to access a PHP array file from a server using JSON in JavaScript for data visualization?

I am currently attempting to access a .php file on a server through my Netbeans software using JavaScript with JSON. As a beginner, I have been struggling to find a solution to this issue. Within the developers tool, I am encountering the following error ...

Why does one image render while the other with the same src does not?

Has anyone encountered a situation where there are 2 img tags with the same src, "images/export.png", but one displays correctly while the other doesn't? Any insights on how this discrepancy can occur? https://i.sstatic.net/z6rnW.png Here's som ...

In a jQuery conditional statement, selecting the second child of the li element for targeting

I'm encountering an issue where I can't target the second child of an li element and use it in a conditional statement. Are jQuery conditionals not compatible with li:nth-child(2)? if($(".steps ul li:first-child").attr('aria-selected') ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

Utilizing promise values within asynchronous functions

I know this question has been asked multiple times, but I'm facing a situation where I need to retrieve a variable created within a promise. The examples I've come across involve using .then to access the data, but in my case, I need to work with ...

Struggling with incorporating a lightbox within an accordion feature in an .html file

I'm currently attempting to integrate this lightbox into this accordion feature. Individually, I've managed to get both elements up and running smoothly. However, when trying to combine them on the same page (regardless of nesting one inside the ...

What is the best way to store a video file in a database?

Recently, I came across a task where I needed to insert a video in a database and display it using an HTML5 video control. Despite successfully saving the video in the database, I encountered an issue when trying to play the video. Upon investigating, I ...

Why am I unable to choose an element by its Id?

My goal is to pass an ID as an argument to a function in the following manner: HTML <button type="button" class="like btn" onclick="like('<%=postid%>')"> <svg id ='<%=likei ...

Disposing of memory in THREE JS when switching between routes in VUE

Currently, I am delving into the world of VUE JS and working on a basic SPA that navigates through different pages. In my spare time, I have developed several THREE JS demos which unfortunately tend to slow down and eventually halt when switching between ...

Looking to update the URL from another component?

My current project is using Angular 6 and I am working on creating a list of buttons on the left panel such as "Ice cream", "Pop corns", and more. The goal is for users to click on these buttons which will then change the URL of the add button located in t ...

Having trouble with the setHours function in React not behaving as anticipated?

I'm having trouble adjusting the time in my React application using the setHours method: function App() { let currHour = new Date().setHours(15); return ( <div> <h1>{currHour}</h1> </div> ); } Inst ...

Ways to extract link value in Angular

Is there a way to extract a value from a link using Angular 4? I have used *ngIf and would like to display a div based on the value within the link. <div *ngIf="obtain the value from the current href"> ...

What is the term used for the objects that res.render passes?

I constantly find myself struggling with defining objects inside res.render. Is there a way to define them globally or outside of res.render? I hope someone can offer some guidance.. here is a sample code snippet: router.get("/home/blog", function(req,r ...

Circular dependency situation encountered in Angular 2 shared module

I'm currently working on a share module setup that is structured as follows: @NgModule({ exports: [ CommonModule, HttpModule, OneModule, TwoModule ] }) export class SharedModule { } The OneModule imports the SharedModule in order ...

A step-by-step guide to loading a .php file via Ajax using JQuery when an item is selected from a dropdown

I have successfully populated a dropdown list using PHP from a database on the page named admin.php. Now, I am utilizing JQuery with Ajax functionality to display information when a surname is clicked from the dropdown menu. The goal is to call employerP ...

Automatically activate a button when it comes into view while scrolling

I am currently working in Joomla, which makes it challenging to create a fiddle, but here is the concept: My website displays a mosaic grid of 12 articles upon loading, along with a 'Load More' button. When this button is clicked, an additional ...

Function not currently in operation

There seems to be an issue with the script not running or returning any answers. The console is blank. I am attempting to retrieve an answer from the Yandex Translate site (https://tech.yandex.com/translate/doc/dg/reference/translate-docpage/) Code: http: ...