Just noticed today that template literals with html tags don\'t work, or maybe I wrote it wrong?
I tried to include p tags in the template literals (which I commente
Templates are needed to be enclosed in backticks. You don't need to enclose template in quotes again.
You need to change this:
'`${i.name} is a ${i.species}.
`'
to this:
`${i.name} is a ${i.species}.
`
The former is just a plain JavaScript string, but the latter is the template literal syntax and it allows the sections in ${ ... } to be interpolated.
See the following working example:
var blueBtn = document.getElementById('btn');
var aniBox = document.getElementById('animal-info');
blueBtn.addEventListener('click', function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
addHTML(ourData)
};
ourRequest.send();
});
function addHTML(data) {
var content = '';
for (let i of data) {
console.log(i);
// content += '' + i.name + ' is a ' + i.species + '.
';
content += `${i.name} is a ${i.species}.
`;
}
aniBox.insertAdjacentHTML('beforeend', content);
}
JSON and AJAX
JSON and AJAX
Read more about template literals in the documentation.