Busco algunos datos con api y quiero usarlos y mostrarlos en mi página HTML usando javascript puro. Mi HTML actual:
<button onclick="load()">Load data</button> <div id="main"></div>Mi estructura esperada para usar datos API:
<div id="main"> <div class="wrapper"> <img src="link will come from API" class="img-class"> <h6 class="title"></h6> </div> <div class="wrapper"> <img src="link will come from API" class="img-class"> <h6 class="title"></h6> </div> <div class="wrapper"> <img src="link will come from API" class="img-class"> <h6 class="title"></h6> </div> <div class="wrapper"> <img src="link will come from API" class="img-class"> <h6 class="title"></h6> </div> . . . . . .... </div>Aquí está mi js:
function load(){ fetch("https://jsonplaceholder.typicode.com/photos") .then(function(response){ return response.json() }) .then((response)=>{ var counter=0; for (var data of response) { if(counter == 99){ break; alert("end"); }else{ var wrapper = document.createElement('div'); var img = document.createElement('img'); img.src = data.url; img.setAttribute("class","img-class"); document.getElementById('main').appendChild(img); document.getElementById('main').appendChild(img); counter++; } } }) }Pude cargar imágenes pero ahora quiero hacer una estructura adecuada. Aquí está funcionando el enlace de Copen.
Puede crear cada elemento, establecer los atributos y luego agregarlo a su elemento principal. Como no especificó la estructura de los datos que devuelve su API, tendrá que cambiar el código para admitir su API. En tu caso, algo como esto debería funcionar.
for (var data of response) { const imageUrl = data['image'] // you'd want to change this const wrapperDiv = document.createElement('div'); wrapperDiv.classList.add('wrapper'); const imgElem = document.createElement('img'); imgElem.src = imageUrl; imgElem.classList.add('img-class'); wrapperDiv.appendChild(imgElem); // You didn't specify what you wanted // to do with the title so make sure to add // to this part. const titleElem = document.createElement('h6'); titleElem.classList.add('title'); wrapperDiv.appendChild(titleElem); document.getElementById('main').appendChild(wrapperDiv); }simplemente agregue img a la wrapper
wrapper.appendChild(img) luego agregue el wrapper al documento
document.getElementById('main').appendChild(wrapper)