How can i make only the one i choose to hide?

Suppose i have 100 buttons, and i wanna make hide only 1, but i made the buttons with a for, is there a way to make that?

!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

<!-- begin snippet: js hide: false console: true babel: false -->
for(i=1;i<=3;i++)
$(document).ready(function(){
  $("#i").click(function(){
    $("#i").hide();
  });
});

</script>
</head>
<body>

<button id="1">Hide</button>
<button id="2">Hide</button>
<button id="3">Hide</button>
</body>
</html>

Answer

Try this,

for (let i = 1; i <= 3; i++)
    $(`#${i}`).click(function(){
      $(this).hide();
    });

Use the for loop inside the $(document).ready and use this instead of again querying the button

Leave a Reply

Your email address will not be published. Required fields are marked *