Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 21 Jun, 2021
Geek Week

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:

  • First, we add a click event on the div element that contains a paragraph element using the on() function in JQuery.
  • And then to make the click event workable only on the parent element, we call a function that checks whether the clicked element is the parent element or not. If it is a parent, we call an alert() function. Otherwise, We don’t do anything.
  • The function looks like this:
$('.parent').on('click', function(e) {
    if (e.target == this){
        alert( 'clicked on parent element' );
    }
});

Example 1:

HTML




<!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:

HTML




<!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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :