Home > database >  Escaped characters appearing when appending to HTML element
Escaped characters appearing when appending to HTML element

Time:05-19

I am fetching HTML code via an AJAX call, and then appending the code it to an existing HTML element. Problem is, the appended code contains escaped characters, causing the HTML to break, and resulting in haphazard elements looking like this: Contact Us ▸<\/a><\/li>\n: Contact Us ▸</a></li>\n

The HTML element is: <li ><a href="https:\/\/website.com\/contact" >Contact Us ▸&lt;\/a&gt;&lt;\/li&gt;\n</a></li>

For reference, the ajax response received is:

"<li class='listitems'><a href='https:\/\/website.com\/contact' class='listlinks'>Contact Us &rtrif;<\/a><\/li>\n"

And the JavaScript code used to add this to the existing ul element is:

let r = httpRequest.responseText; // The AJAX response
document.getElementById('mylist').insertAdjacentHTML("beforeend",r);

I've also tried using the following:

let r = httpRequest.responseText; // The AJAX response
document.getElementById('mylist').interHTML  = r;

but am observing the same results.

However, when I try either JavaScript code in the browser's console: I get the expected results: Contact Us ▸Contact Us ▸

And the HTML element is: <li ><a href="https://website.com/contact" >Contact Us ▸</a></li>

I am unable to understand why the code is not being unescaped and evaluated as HTML normally, but it works when I do it manually using the browser's console window.

Can anyone tell me what I'm missing here and how I can fix this?

CodePudding user response:

The response is JSON, you need to parse it.

let responseText = `"<li class='listitems'><a href='https:\\/\\/website.com\\/contact' class='listlinks'>Contact Us &rtrif;<\\/a><\\/li>\\n"`;
let r = JSON.parse(responseText);
document.getElementById('mylist').insertAdjacentHTML("beforeend",r);
<ul id="mylist">
</ul>

  • Related