jQuery > Selectors

Closest selector in jQuery

How to select closest element on click event in jQuery?


To select closest element on click event of jQuery, we shall use .closest function.

In below code snippet, we have three paragraphs and each paragraph has <b>, <i> and <u> element respectively.

   <style type="text/css">
       .back { 
           background-color:blueviolet;
       }
   </style>

    <p>This is paragraph <b>1</b></p>
    <p>This is paragraph <i>2</i></p>
    <p>This is paragraph <u>3</u></p>

    <script>
        $(function () {
            $("body").on('click', function (e) {
                $(e.target).closest("p").toggleClass("back");
                alert(e.target.nodeName);
            });
        });
    </script>

In the <script> block, we have attached click event on body by using element selector using .on function. When the body of the page is clicked, the function is called with the event argument (e).

e.target will give us the element that has been clicked and then we are finding the closest <p> element (the first parent element) and toggling "back" class. After that it also give us the node name (for verification purpose) that was clicked by the user just to know if the toggling effect is happening to the correct element or not.

 Views: 6757 | Post Order: 25



Write for us






Hosting Recommendations