async function getJson() {
const requestURL = 'https://jsonplaceholder.typicode.com/posts';
const request = new Request(requestURL);
const response = await fetch(request);
const json = await response.json();
displayData(json);
}
function displayData(json) {
json.forEach((i) =>
document.getElementById(`${i.id}`).insertAdjacentHTML(
'beforeEnd',
` <h2>Id: ${i.id}</h2>
<h3>${i.title}</h3>
<p>${i.body}</p>
`
)
);
}
getJson();
<section>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
</section>
TypeError: Cannot read properties of null (reading 'insertAdjacentHTML').
Странно, но все работает, несмотря на ошибку:
TypeError: Cannot read properties of null (reading 'insertAdjacentHTML').
arr.forEach(n => {
const el = document.getElementById(n.id);
if (el) {
el.innerHTML = `
<h2>Id: ${n.id}</h2>
<h3>${n.title}</h3>
<p>${n.body}</p>
`;
}
});
for (const { id, title, body } of arr) {
document.querySelector(`[id="${id}"]`)?.insertAdjacentHTML('beforeend', `
<h2>Id: ${id}</h2>
<h3>${title}</h3>
<p>${body}</p>
`);
}
section
изначально будет пустым):document.querySelector('section').innerHTML = arr
.map(n => `
<div id="post-${n.id}">
<h2>Id: ${n.id}</h2>
<h3>${n.title}</h3>
<p>${n.body}</p>
</div>`)
.join('');
const limit = document.querySelector('section').children.length;
const requestURL = `https://jsonplaceholder.typicode.com/posts?_limit=${limit}`;
const requestURL = 'https://jsonplaceholder.typicode.com/posts?' + Array
.from(document.querySelector('section').children, n => `id=${n.id}`)
.join('&');