Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda