Computer >> Computer tutorials >  >> Programming >> Javascript

Toggle hide class only on selected div with JavaScript?


To toggle hide class only on selected div, you need to set event on click button. Let’s say you need to hide a specific div on the click of + sign.

To get font + or - icon, you need to link font-awesome −

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/
4.7.0/css/font-awesome.min.css">

Following is the code to toggle hide class on clicking + sign −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/fontawesome.
min.css">
<style>
.hideDiv {
display: none;
}
</style>
</head>
<body>
<div class="firstDetails">
<h2 class="customer-track">Customer 1<i class="fa fa-plus"></i></h2>
<div>
<p class="customer">John</p>
<p class="customer">US</p>
</div>
<div class="secondDetails">
<h2 class="customer-track">Customer 2 <i class="fa fa-plus"></i></h2>
<div>
<p class="customer">David</p>
<p class="customer">AUS</p>
</div>
</div>
</div>
<script>
$(".fa-plus").on("click", function(){
$(this).parent().siblings('.secondDetails').toggleClass("hideDiv");
});
</script>
</body>
</html>

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.

Output

This will produce the following output −

Toggle hide class only on selected div with JavaScript?

After clicking the plus icon besides “Customer1”, you will get the following output i.e. Customer2 div will vanish −

Toggle hide class only on selected div with JavaScript?