Reputation: 49
I have a website and want to display text. The text is in German and comes from a JSON data set I have. This is retrieved from a localhost API URL for now. The German words have the special characters replaced with HTML encoded ones. For example, erzählt is saved in the JSON data as erzählt. When I make the textContent of my paragraph tag to the JSON German text, the HTML encoding does not work. It does work however if I just copy and paste it manually in. How can I trigger the encoding to work and have it show correctly?
Code: Gets random German word from JSON API, puts text into paragraph. Encoding issue. erzählt is shown instead of erzählt .
JSON example:
{ "id": "32", "ename": "Smile.", "gname": "Lächeln!" }
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
</head>
<h4>German:</h4>
<div>
<p id="gname">
</div>
<script>
const api_url = 'http://localhost:3000/fyp/api/grandom.php';
async function getData() {
const repsonse = await fetch(api_url);
const data = await repsonse.json();
var i = Math.floor((Math.random() * 16534) + 0);
const { gname, ename } = data[i];
document.getElementById('gname').textContent = gname;
document.getElementById('ename').textContent = ename;
}
getData();
</script>
Any help or advice appreciated. If anything needs explaining please let me know.
Upvotes: 0
Views: 277
Reputation: 534
use innerHTML instead of innetText to solve your problem
function getData() {
const data = { "id": "32", "ename": "Smile.", "gname": "Lächeln!" };
document.getElementById('gname').innerHTML = data.gname;
document.getElementById('ename').innerHTML = data.ename;
}
getData();
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
</head>
<body>
<h4>German:</h4>
<div>
<p id="gname"></p>
<p id="ename"></p>
</div>
<body>
Upvotes: 0
Reputation: 943605
If your string contains HTML entities like ä
then it isn’t text, it is HTML.
textContent
expects you to pass plain text to it, not HTML source code.
Use innerHTML
instead.
const value = "erzählt";
text.textContent = value;
html.innerHTML = value;
<div id=text></div>
<div id=html></div>
Upvotes: 1