I'm a beginner in js, so the question I'm going to pose may be super easy, but I can't find the solution. I have an array of objects (a website that simulates a service reservation site) with their properties. However; I would like to access the name property of each object and put that name as an h2 in its corresponding div and I can't do it. I then pass the html and js to be able to display it better
Here the html:
<div class="container">
<div class="row">
<div class="col">
<img src="media/toalla_velas.jpg" alt="">
</div>
<div class="col">
<img src="media/mujer_recibiendo_masajes.jpg" alt="">
</div>
<div class="col">
<img src="media/spa-treatment-over-dark-wall.jpg" alt="">
</div>
<div class="col">
<img src="media/terapia_facial.jpg" alt="">
</div>
<div class="btn">
<button id="see-btn" class="btn-see reserve">Ver más</button>
<button id="reserve" class="reserve">Reservar</button>
</div>
</div>
Necesito que dicho h2 esté en cada div con clase "col", arriba de la foto correspondiente.
A continuación muestro el array y las funciones:
const services = [{id: 1, name: 'service 1', price: 30},
{id: 2, name: 'service 2', price: 35},
{id: 3, name: 'service 3', price: 35},
{id: 4, name: 'service 4', price: 30}]
function addTitle() {
let col = document.getElementsByClassName('col');
let title = document.createElement("h2");
findId(services, services.id);
title.createTextNode(`${services.name}`)
services.forEach(service => {
col.innerHTML.prependChild(title)
});
}
function findId (objects, id) {
const index = objects.findIndex(object => object.id == id);
console.log(objects[index].name)
return index
}
This can be an option, it is recommended that if each box has something different, it is assigned an id and not work everything with the class.