Is there a way to get inside of a div on click and get the text content of an h2 element?

I’m trying to make a generic shopping cart

So basically, I have a div that has multiple h2 elements within it.

on my button click i’m getting the entire container div which is what I want because I’m moving the entire div to the shopping cart on click.

However, there is an h2 within that div that I need to target specifically, and I don’t understand how to.

e.target.parentElement brings back the entire div on click.

I’m trying to add another property to go within that div and get the text content of the h2 within it.

Is there any way to do this? Sorry if it’s worded oddly

for (i=0; i<addToCartButtons.length; i++) {
    addToCartButtons[i].addEventListener('click', (e) => {
        cartContainer.innerHTML += e.target.parentElement.innerHTML
        console.log(e.target.parentElement.)
    })
}

Hey there @Tsmithcode ! If you can , why don’t you give the h2 element an id. If you can’t comment on this and i’ll try to reply soon as i can.

Can you target by class? (If all of these have a specific class for eg?)

Or use document.querySelector(“div > h2”) perhaps

I still don’t know how to target it on button click even with an ID

e.target.parentElement

what would I add onto that to target the h2 on click?

I have a codepen that shows how to do an html update on click.

e.target.parentElement.firstElementChild.nextElementSibling.textContent

this worked! I’m so happy!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.