3

Thanks to anyone who helps me solve this issue.

So the issue is I'm trying to hide an element (by class) with an onclick event using a button. But I am unable to do so.

Here's the code on jsfiddle http://jsfiddle.net/1tpdgrnj/

Here's the code for those who wish to help me here:

HTML:

<div class="box">Hide on button click!!
<button onclick="close();">Close</button>

Javascript:

function close() {
document.getElementsByClassName("box").style.display = 'none';}

UPDATE

Refer to the answer below and to the jsfiddle to see how it's different.

Lal
  • 14,726
  • 4
  • 45
  • 70
Saumya Banthia
  • 127
  • 1
  • 3
  • 9

3 Answers3

4

See this fiddle

Change your javascript as follows

function myFunction() {
    document.getElementsByClassName("box")[0].style.display = 'none';
}

First change that should be done is, rename your function name, as close is a keyword in Javascript.

Second one is that, document.getElementsByClassName() returns an array and thus to get the first element you should use the index position 0.

According to the docs

The Element.getElementsByClassName() method returns a live HTMLCollection containing all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.

Read more about it here

Lal
  • 14,726
  • 4
  • 45
  • 70
0

You can use Jquery

<div class="box">Hide on button click!!
    <button class="close">Close</button>

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
    $(document).ready(function(){
    $(".close").click(function(){
        $(this).parent().hide(); return false;

    });
    });
    </script>
frank_ivan
  • 123
  • 5
-1

Check this fiddle

You can also do this easily with jQuery.

$("#hide").click(function(){
    $(".box").fadeOut(150);
});
kwh71787
  • 576
  • 1
  • 4
  • 14