Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
How to add addEventListener to from parent to child in pure Javasvript?

i need your help. My code structure is like this:

<div class="header">
  <p>Button</p>
  <ul>
    <li>Option 1</>
    <li>Option 2</>
    <li>Option 3</>
  </ul>
</div>

i want to use addEventListener here on p tag, on clicking it we need to hide and show ul. This is one of my friends challenge question, please anyone help me how to achieve this. p tag is inside header class. I cannot change the format, need to impliment like this. I want to use pure javascrript for this problem

Codepen Link:

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Select the DOM through the selector, add click events, switch variables

const header = document.querySelector('.header')
const btn = header.querySelector('p')
const ul = header.querySelector('ul')
let isShow = false
btn.addEventListener('click', () => {
  isShow = !isShow
  ul.style.display = isShow ? 'none' : 'block'
})
<div class="header"> <p>Button</p> <ul> <li>Option 1</> <li>Option 2</> <li>Option 3</> </ul> </div>

about 4 years ago · Santiago Trujillo Report

0

In case you want to add it to multiple elements

const toggleVisibilityOfEl = (el) => el.style.visibility = (el.style.visibility == 'hidden' ? 'visible' : 'hidden')

// in case you add classes you can add the path to the element/ element here
const allPElements = document.querySelectorAll('p');
const allUlElements = document.querySelectorAll('ul')

 allPElements.forEach(e =>
    e.addEventListener('click', (event) =>
      allUlElements.forEach(toggleVisibilityOfEl)
    )
  )
<div class="header">
  <p>Button</p>
  <ul>
    <li>Option 1</li>
    <li>Option 2</li>
    <li>Option 3</li>
  </ul>
</div>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!