Primera vez que publico aquí :)
Recientemente comencé a codificar y para practicar el estudio de JS, quería hacer un botón en mi barra de navegación que genera un objeto para DOM después de hacer clic en él. ¿Puede indicarme los pasos para agregar y agregar elementos que necesito crear dentro de la función addToDom? Parece que mezclo el proceso y después de múltiples fallas he dejado el espacio en blanco.
PD ¿Estoy vinculando img correctamente?
Mi código actual hasta ahora:
const Kirstin = { firstName: 'Kirstin', lastName: 'Ortega', image: "img:resources/kirstin ortega.gif", alias: 'Police officer', getfullName: function(){ this.firstName + ' ' + this.lastName; }, addToDom: function(firstName, lastName, image, alias, getfullName,){ } } const bodyElement = document.querySelector("btn1"); bodyElement.addEventListener("click", function (){ addToDom(this.firstName, this.lastName, this.image, this.alias, this.getfullName); });ACTUALIZAR Estoy tratando de replicar la misma estructura en el archivo HTML de la siguiente manera:
<article class = "articleTakeshi"> <div class="cardTakeshi"> <img src="resources/takeshi kovacs.gif" alt="Avatar"> <div class="container"> <h2>Takeshi Kovacs</h2> <p>The Last Envoy</p> </div> </div> </article>Entonces, básicamente, mi objetivo es crear un nuevo artículo con la misma estructura que se muestra arriba usando Javascript.
Prueba esto:
<html> <body> <button id="btn1">Add</button> <div id="list"> <article class="articleTakeshi"> <div class="cardTakeshi"> <img src="https://www.gravatar.com/avatar/6c488c6599d9a5855d7a5e5dbef2883f?s=48&d=identicon&r=PG" alt="Avatar"> <div class="container"> <h2>Takeshi Kovacs</h2> <p>The Last Envoy</p> </div> </div> </article> </div> <script> function createElementFromHTML(htmlString) { var div = document.createElement('div'); div.innerHTML = htmlString.trim(); // Change this to div.childNodes to support multiple top-level nodes. return div.firstChild; } const Kirstin = { firstName: 'Kirstin', lastName: 'Ortega', image: "https://graph.facebook.com/10219900817020254/picture?type=large", alias: 'Police officer', } const addToDom = function ({ firstName, lastName, image, alias, getfullName }) { function render() { return createElementFromHTML(` <article class="article${firstName}"> <div class="card${firstName}"> <img src="${image}" alt="Avatar"> <div class="container"> <h2>${firstName} ${lastName}</h2> <p>${alias}</p> </div> </div> </article> `) } document.querySelector("#list").appendChild(render()) } const bodyElement = document.querySelector("#btn1"); bodyElement.addEventListener("click", function () { addToDom(Kirstin); }); </script> </body> </html>¿Cómo funciona?
createElementFromHTML creará un elemento DOM a partir de una cadena html.
Al hacer clic en el botón cuya identificación es btn1, se llama a addToDom con el argumento Kirstin , que es un objeto.
La función addToDom extraerá todos los campos:
firstName, lastName, image, alias, getfullNamecomo función de variables locales.
y usando estas variables, la función render devuelve una cadena html renderizada y la convertimos a un DOM. Luego lo agregamos al final de #list .