Michael Michael - 4 months ago 23
jQuery Question

Element not hidden when button is clicked

Why

display = "none"
not works when button is clicked in jsFiddle?

HTML:

<div>This is a visible heading<div>
<div class="hidden">This is a hidden heading</div>
<div>Notice that the hidden heading still takes up space.</div>

<hr/>




JavaScript:

$('input[type=button]').click( function() {
document.getElementsByClassName("hidden").style.display = "none";
});

Answer

document.getElementsByClassName() returns HTMLCollection which is an Array like object. You are trying to apply HTML Node properties on this array.

First select DOM Node from this array then apply style properties as shown below.

document.getElementsByClassName("hidden")[0].style.display = "none";

$('input[type=button]').click( function() {
 document.getElementsByClassName("hidden")[0].style.display = "none";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>This is a visible heading<div>
<div class="hidden">This is a hidden heading</div>
<div>Notice that the hidden heading still takes up space.</div>

<hr/>

<input type="button" value="test" />

Alternatively you can use jQuery to hide element.

$('input[type=button]').click(function() {
  $(".hidden").first().hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>This is a visible heading<div>
  <div class="hidden">This is a hidden heading</div>
  <div>Notice that the hidden heading still takes up space.</div>

  <hr/>

  <input type="button" value="test" />

In Pure JavaScript you can do it as follows:

var button = document.getElementsByClassName('button')[0];

button.addEventListener('click', function() {
 document.getElementsByClassName("hidden")[0].style.display = "none";
}, false);
<div>This is a visible heading<div>
<div class="hidden">This is a hidden heading</div>
<div>Notice that the hidden heading still takes up space.</div>

<hr/>

<input class="button" type="button" value="test" />