I have a few boxes that each of them contained button and a <p> element that its innerText was create by data from an API. I put an onclick on each box (the <div> that wrap the <p> element and the button). I want every time the button is clicked, the innerText of the <p> tag that is "sitting" next to the this button, in the same div, will console log. Can’t figure this out at the moment, this is what I have got so far:
const containerShapes = document.getElementById("container-pock-shape")
fetch("https://pokeapi.co/api/v2/pokemon-shape")
.then(res => res.json())
.then(data => data.results.map(item => {
return containerShapes.innerHTML +=
`<div class="shape-box" onclick="showName(event)">
<p>${item.name}</p>
<button>Select</button>
</div>`
}))
function showName(e) {
console.log()
}
#container-pock-shape {
display: flex;
flex-wrap: wrap;
}
.shape-box {
border: 2px solid red;
display: flex;
flex-direction: column;
align-items: center;
padding: 10px;
width: 200px;
}
.shape-box p {
background-color: grey;
width: 100px;
text-align: center;
font-weight: 900;
}
<body>
<div id="container-pock-shape">
</div>
</body>
>Solution :
To get the name, since the event is on the entire div, you need to use querySelector and find the inner <p> element and grab its text.
const containerShapes = document.getElementById("container-pock-shape")
fetch("https://pokeapi.co/api/v2/pokemon-shape")
.then(res => res.json())
.then(data => data.results.map(item =>
containerShapes.innerHTML +=
`<div class="shape-box" onclick="showName(this)">
<p>${item.name}</p>
<button>Select</button>
</div>`
))
function showName(box) {
const name = box.querySelector('p').textContent;
console.log(name);
}
#container-pock-shape {
display: flex;
flex-wrap: wrap;
}
.shape-box {
border: 2px solid red;
display: flex;
flex-direction: column;
align-items: center;
padding: 10px;
width: 200px;
}
.shape-box p {
background-color: grey;
width: 100px;
text-align: center;
font-weight: 900;
}
<body>
<div id="container-pock-shape"></div>
</body>
An alternative way to do this would be to add the click event to only the button, and look for the closest shape box and then locate the <p>.
const containerShapes = document.getElementById("container-pock-shape")
fetch("https://pokeapi.co/api/v2/pokemon-shape")
.then(res => res.json())
.then(data => data.results.map(item =>
containerShapes.innerHTML +=
`<div class="shape-box">
<p>${item.name}</p>
<button onclick="showName(this)">Select</button>
</div>`
))
function showName(button) {
const name = button.closest('.shape-box').querySelector('p').textContent;
console.log(name);
}
#container-pock-shape {
display: flex;
flex-wrap: wrap;
}
.shape-box {
border: 2px solid red;
display: flex;
flex-direction: column;
align-items: center;
padding: 10px;
width: 200px;
}
.shape-box p {
background-color: grey;
width: 100px;
text-align: center;
font-weight: 900;
}
<body>
<div id="container-pock-shape"></div>
</body>