jquery How do I hide a single html object being clicked on?

I'm doing jquery tutorial on W3Schools. I ask out of curiosity and learning, that's all. No business applications.

I want to click an HTML element and hide it using one function only.

I click on (h1,h2,p), but it seems that I need to pass the function the tag itself to hide it when using $(this).

I've tried

$(*).click(function(){

but this hides everything. My code is...

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $([the HTML object I'm clicking on now]).click(function(){
        $(this).hide();
    });
});
</script>
</head>
<body>

If you click on me, I will disappear.

Click me away!

Click me too!

Answers 1

  • You have to reference to the objects you want to manipulate on, then use this keyword, to apply the function on a specified (clicked) element.

    $('.box, input, .btn').click(function() {
      $(this).hide();
    });
    .box {
      width: 50px;
      height: 50px;
      background: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class='box'></div>
    <input class='input'>
    <button class='btn'>click</button>


Related Articles