Search code examples
javascriptevent-delegation

Event Delegation, how to target a specific span inside a div


Given a bunch of divs like these:

<div class="itemGrid">
    <div id="itemOne" class="fruit">
       <span> Banana </span>
          🍌
        </div>

     <div id="itemTwo" class="fruit">
        <span> Apple </span>
          🍎
      </div>
</div>

I want to be able, using event delegation, to get the value of the span (so just the text) when I click on those divs.

With this I get everything, the text AND the symbol, but I can't seem to be able to just get the text inside the span:

const fruitButtons = document.querySelectorAll(".fruit span");
const grid = document.querySelector(".itemGrid");

grid.addEventListener("click", function(e) {
  if (e.target.nodeName == "DIV") {
    console.log(e.target.textContent)
  }
})

Solution

  • Reworking the scenario a little:

    const fruitButtons = document.querySelectorAll(".fruit > span");
    const gridItems = document.querySelectorAll(".fruit");
    
    // Loop through the div.fruit elements:
    gridItems.forEach(function(div){
      
      // Wire each div.fruit to a click handler:
      div.addEventListener("click", function(e){
        // When clicked, look for the first span within the div and get its text
        console.log(div.querySelector("span").textContent);
      }); 
    });
    <div class="itemGrid">
        <div id="itemOne" class="fruit">
           <span> Banana </span>
              🍌
         </div>
    
         <div id="itemTwo" class="fruit">
            <span> Apple </span>
              🍎
          </div>
    </div>