admin管理员组

文章数量:1420589

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 /

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.

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/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.

Share Improve this question edited Sep 8, 2015 at 18:50 Lal 14.8k4 gold badges48 silver badges72 bronze badges asked Sep 8, 2015 at 18:37 Saumya BanthiaSaumya Banthia 1371 gold badge3 silver badges9 bronze badges 1
  • possible duplicate of Javascript onclick hide div – Adam Buchanan Smith Commented Sep 8, 2015 at 18:41
Add a ment  | 

3 Answers 3

Reset to default 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 plete document is searched, including the root node.

Read more about it here

You can use Jquery

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

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

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

    });
    });
    </script>

Check this fiddle

You can also do this easily with jQuery.

$("#hide").click(function(){
    $(".box").fadeOut(150);
});

本文标签: javascriptHide DIV element with onclick commandStack Overflow