Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

help refactor my js color buttons

Hi, this works but it seems somewhat verbose, any tips on doing this in a simpler way. I guess the issue I had was getting the class name on the color-div even when clicking on the p elem

Thanks

<div class="container">

    <div class="color-div">
      <p>red</p>
    </div>

    <div class="color-div">
      <p >orange</p>
    </div>

    <div class="color-div">
      <p>green</p>
    </div>
</div>

<script>

const container = document.querySelector('.container');
  container.addEventListener('click',(e)=>{
    if (e.target.tagName == 'P') {

      const pColor = e.target.textContent;
      e.target.parentNode.classList.add(pColor)

    } else if (e.target.className == 'color-div') {

      const pColor = e.target.querySelector('p').textContent;
      e.target.classList.add(pColor);
    }
  }
);

</script>

1 Answer

Steven Parker
Steven Parker
243,318 Points

I'm not sure if this constitutes "simpler", but if you attach handlers directly to the div's and use currentTarget instead of target, you can eliminate the separate case for the paragraphs:

Array.from(document.querySelectorAll(".color-div")).forEach(d => {
  d.addEventListener("click", e => {
    const pColor = e.currentTarget.querySelector("p").textContent;
    e.currentTarget.classList.add(pColor);
  });
}