Open In App

How to bind an event on an element but not on its children in jQuery ?

In this article, we will learn how to bind an event on an element but not on its children in jQuery. We want to add an event on the parent element but not on the child element.

Approach: We can do this task in the following steps:



$('.parent').on('click', function(e) {
    if (e.target == this){
        alert( 'clicked on parent element' );
    }
});

Example 1:




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
  
    <style>
        body {
            color: green;
            font-size: 30px;
        }
  
        div {
            font-size: 40px;
        }
  
        button {
            font-size: 30px;
        }
    </style>
</head>
  
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <div class='parent'>
            click to see changes(parent)
            <p style="color: red;" class="child">
                This will not work(Child)
            </p>
        </div>
    </center>
  
    <script>
        $('.parent').on('click', function (e) {
            if (e.target == this) {
                alert('clicked on parent element');
            }
        });
    </script>
</body>
  
</html>

Output:



Example 2:




<!DOCTYPE html>
<html lang="en">
  
<head>
    <script src=
    </script>
  
    <style>
        body {
            color: green;
            font-size: 30px;
        }
  
        div {
            font-size: 40px;
        }
  
        button {
            font-size: 30px;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
    <ul>
        <li style="color: red;" class='parent'>
            click to see changes(parent)
        </li>
        <ul>
            <li class="child">This will not work(child)</li>
            <ul>
                <li>This will also not work (GrandChild)</li>
            </ul>
        </ul>
    </ul>
  
    <script>
        $('.parent').on('click', function (e) {
            if (e.target == this) {
                alert('clicked on parent element');
            }
        });
    </script>
</body>
  
</html>

Output:


Article Tags :