Tell us what’s happening:
Hello everyone! Today I was trying to solve this challenge. I didn’t like the use of tags as strings of text, so I decided to create variables for each tag:
let br = "<br>"
let strongO = "<strong>"
let strongE = "</strong>: "
However, this code doesn’t pass the last test. It seems like it did wrap my key names in strong
tags… I thought this had to do with scope, but I tried all possible places I could place my variable declarations and it didn’t solve my issue. However, if I follow the example and use the text directly, like html += "<strong>" + key + "</strong>: " + val[key] + "<br>";
everything works. Is my code wrong somewhere else or is it a bug?
Thank you in advance!
Your code so far
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('getMessage').onclick = function(){
const req = new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload = function(){
const json = JSON.parse(req.responseText);
let html = "";
// Add your code below this line
json.forEach(function(val) {
const keys = Object.keys(val)
html += "<div class = 'cat'>"
let br = "<br>"
keys.forEach(function(key) {
let strongO = "<strong>"
let strongE = "</strong>: "
html += strongO + key + strongE + val[key] + br
})
html += "</div>" + br
})
// Add your code above this line
document.getElementsByClassName('message')[0].innerHTML = html;
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0
Challenge: JSON APIs and AJAX - Convert JSON Data to HTML
Link to the challenge: