Skip to content
Advertisement

Working with event handlers in Javascript

const divs_demo = document.querySelectorAll('.common');
const display_texts = document.querySelectorAll('.text');



for(let div_demo of divs_demo){
    div_demo.addEventListener('click', ()=>{
        for(let display_text of display_texts){
            display_text.style.display = 'block';
        };
    });
};
.text{
    display: none;
}
.common{
    border: 1px solid;
}
<body>
    
    <div class="common">
        <h1>Text one</h1>
        <p class="text">Hello</p>
    </div>
    <div class="common">
        <h1>Text two</h1>
        <p class="text">Good morning</p>
    </div>
    <div class="common">
        <h1>Text three</h1>
        <p class="text">Lets code</p>
    </div>

    <script src="app.js"></script>
</body>

Am working on with event handlers in JavaScript, however, have encountered a problem on my way, on the above code, I have got access to all the div elements in my html, and some hidden text which I want it to be displayed once the event handler which I have passed to the divs is performed, but once one div is clicked, it displays the all the text including the one on the other divs, but my target is to only display the text on the div which is clicked. Is there a way to do that without repeating the same code to every div?

Advertisement

Answer

Do you mean this?

const divs_demo = document.querySelectorAll('.common');
const display_texts = document.querySelectorAll('.text');

for (let div_demo of divs_demo) {
  div_demo.addEventListener('click', () => {
    div_demo.querySelector(".text").style.display = 'block';
  });
};
.text{
    display: none;
}
.common{
    border: 1px solid;
}
<body>
    
    <div class="common">
        <h1>Text one</h1>
        <p class="text">Hello</p>
    </div>
    <div class="common">
        <h1>Text two</h1>
        <p class="text">Good morning</p>
    </div>
    <div class="common">
        <h1>Text three</h1>
        <p class="text">Lets code</p>
    </div>

    <script src="app.js"></script>
</body>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement