I have created 10 , each display one id in API. I have used querySelectorAll to find all the and use for loop to make the content of each contains one id in API but when I try to code, as you can see, one will contain all ten id and I don't know how to make it possible
function onResponse(response) {
return response.json();
}
function data(data) {
//create a function to display the element
var htmls = data.map(function(post) {
return `<li>
<h2> ${post.id}</h2>
</li>`
});
var html = htmls.join('');
const p = document.querySelectorAll('span');
for (let i = 0; i < p.length; i++) {
p[i].innerHTML = html;
}
}
fetch('https://jsonplaceholder.typicode.com/users').then(onResponse).then(data);
<body>
<form>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</form>
</body>
</html>
html is already the HTML of each id. You are assigning it to each span's innerHTML, causing there to be 9 duplicates.
Instead, just assign to the span's parent's innerHTML:
function onResponse(response) {
return response.json();
}
function data(data) {
//create a function to display the element
var htmls = data.map(function(post) {
return `<li>
<h2> ${post.id}</h2>
</li>`
});
var html = htmls.join('');
const div = document.querySelector('div');
div.innerHTML = html;
}
fetch('https://jsonplaceholder.typicode.com/users').then(onResponse).then(data);
<body>
<form>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</form>
</body>
</html>