How to reach outside of a div in an HTMLDivElement object with Javascript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to reach outside of a div in an HTMLDivElement object with Javascript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have several HTML elements that represent tiles to be flipped on click. Each element has a container div, which holds two divs, one for the front and back of the tile.

<div class="flip-container" data-tile>
    <div class="flipper">
      <div class="front white">
        <!-- front content -->
      </div>
      <div class="back blue">
        <!-- back content -->
      </div>
    </div>
  </div>

I have the animation worked out in CSS so the tiles “flip” on hover. So far so good. Now I am trying to change the classList of the “flip-container” on click, so that a different className will be called from my style sheet.

My problem is that my handleClick function is targeting only the inner-div “back-blue”, and not the “flip-container” that is holding both divs.

const tileData = document.querySelectorAll('[data-tile]')
const flipContainers = Array.from(
  document.getElementsByClassName('flip-container')
)


flipContainers.forEach((container) => {
  container.addEventListener('click', handleClick, { once: true })
})

function handleClick(e) {
  console.log('clicked')
  const container = e.target
  const currentClassColor = 'blue'
  fixColor(container, currentClassColor)
}

function fixColor(container, currentClassColor) {
  container.classList.add(currentClass)
}

I have tried querying the “flip-container” both by selecting the data tag and also by grabbing an array from the specific className. In both cases, the entire element is still grabbed, and the target of the click applies only to the inner div. I guess it makes sense why this happening, but is there a way I can access the container even if the click target is one of the inner divs?

Answer

e.target is the div that was clicked, if you want the div that the event handler is attached to you can use the this keyword or e.currentTarget.

function handleClick(e) {
  console.log('clicked')
  // const container = this
  const container = e.currentTarget
  const currentClassColor = 'blue'
  fixColor(container, currentClassColor)
}
We are here to answer your question about How to reach outside of a div in an HTMLDivElement object with Javascript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji