i need your help. My code structure is like this:
<div >
<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
CodePudding user response:
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'
})
CodePudding user response:
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 >
<p>Button</p>
<ul>
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</div>