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.

1

3 Answers 3

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

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

3 Comments

Thanks so much it worked like a charm. Yup was messed up the whole day. Thanks for the help anyways man.
Great.. :) Glad that it helped you.. :)
Yup will do. :D Edit: it says I can select after 4 mins.
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>

Comments

-1

Check this fiddle

You can also do this easily with jQuery.

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

1 Comment

Although the above worked out for me, but thanks for providing an alternative.

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.