1

I'm sure I am missing something really easy here but I am just trying to add a click event to one of my elements but the console keeps stating 'Null is not an object'

Here is my markup

<section class="section active">
  <div class="hidden-content">

  </div>
  <button class="button"></button>
</section>

<section class="section">
  <div class="hidden-content">

  </div>
  <button class="button"></button>
</section>

<section class="section">
  <div class="hidden-content">

  </div>
  <button class="button"></button>
</section>

The javascript I am using

document.querySelector('.section.active .button').addEventListener('click', function(){
     document.querySelector('.section.active .hidden-content').classList.add('show')
});

I know I could do a queryselectorAll like this and add the click handler

var hiddenContent = document.querySelectorAll('.button');
for (var i = 0; i < button.length; i++) {
    button[i].addEventListener('click', function(){
         document.querySelector('.section.active .hidden-content').classList.add('show')
    });
}

The reason I'm asking is I know that there would only ever be one (section.active .button) at any one time which is why i was surprised queryselector wouldn't work for me as it would only return the first one it found which would be this. (Unless I am wrong of course)

Appreciate any advice to where I have gone wrong.

Thanks

1 Answer 1

2

The problem is that you're adding the click handler to the div, which is hidden, so it never receives and clicks (it has zero size). Putting anything at all in your div makes it clickable.

https://jsfiddle.net/8v0w0nrf/

If you want the action to happen on the buttons instead, select for them.

Using the ".hidden-content" div, like before:

var div = document.querySelector('.section.active .hidden-content');
div.parentElement.querySelector('.button').addEventListener('click', function(){
    //Do something
});

Or, you can just go straight to the button:

document.querySelector('.section.active .button').addEventListener('click', function() {
    // Do something
});

Be careful though, you're going to need to update this event listener any time the section.active class changes.

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks Aaron for this. I just realised an error in my markup though. It's actually the button that will have the click handler and not the hidden-content. My fault there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.