Menu Close

How To Filter Div Elements Using Jquery

filter div elements

Here, we will learn about filter elements. Simply we will filter the div elements using jquery with the support of id and classes.

The below html snippet shows the group of buttons with ids which will point to the classes they are intended to filter and a parent element contains all of the div elements with their classes.

Example:

Create a html file and add the jquery codes to the bottom of this file.

<!DOCTYPE html>
<html> 
<head>
    <title>How To Filter Div Elements Using Jquery</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <link rel="stylesheet" href="style.css">
</head>  
<body>
<button class="active btn" id="all">Show All</button>
<button class="btn" id="p1">Show P1</button>
<button class="btn" id="p2">Show P2</button>
<button class="btn" id="p3">Show P3</button>
<button class="btn" id="p4">Show P4</button>
<div class="spacer"></div>
<div id="parent_elements">
  <div class="box p1 p2">P1 &amp; P2</div>
  <div class="box p1">P1</div>
  <div class="box p2">P2</div>
  <div class="box p3">P3</div>
  <div class="box p4">P4</div>
</div>  
</body>
<script>
    var $btns = $('.btn').click(function() {
        if (this.id == 'all') {
    $('#parent_elements > div').fadeIn(450);
        } else {
    var $el = $('.' + this.id).fadeIn(450);
    $('#parent_elements > div').not($el).hide();
        }
    $btns.removeClass('active');
    $(this).addClass('active');
    })
</script>
</html>
 

CSS:

Link the below stylesheet to your html file to view with better design.

body {
    margin: 50px;
    font-family: Arial, sans-serif;
    padding: 10px;
    background: #ecf0f1;
}
.btn {
    border: none;
    background:#FF6000;
    color: #ffffff;
    padding: 5px 10px 5px 10px;
    text-decoration: none;
    margin: 15px;
}

.active {
    background:#333;
    text-decoration: none;
    color: #ffffff !important;
}
.box {
    background:#FF6000;
    padding: 20px;
    width: calc(15% - 10px);
    float: left;
    margin: 15px;
    text-align: center;
    color: #fff;
}
.spacer {
    clear: both;
    height: 30px;
} 
Posted in HTML, jQuery

You can also read...