Last Updated: June 26, 2023
·
486.6K
· becomingGuru

jQuery .find and .closest are your best friends

The .closest and .find selectors are complements of each other and used together are the best way to get to the corresponding element of where the click (or any event) occurred.

From the documentation (paraphrased):

  • The .closest selector traverses up the DOM to find the parent that matches the conditions.
  • the .find selector traverses down the DOM where the event occurred, that matches the conditions.

Now, given these and since the event is always passed as the attribute to the bound function, following is the simplest, best method to get to the corresponding element somewhere:

data = $(event.target).closest('element-row').find('.title');

If you got what I am saying, that is all. But I will try to explain it with an example for those it is not already clear.

Let's consider the following HTML; and let's say you want the title content on clicking Send email.

<div class="element-row">
    <div class="title-row">
        <img src="" />
        <a class="title" href="">Title Goes here</a>
    </div>
    <div class="description-row">
        <p>Description goes here</p>
        <button class="descr-button">Get title</button>
    </div>
</div>

The simplest way to get the title on clicking the button, would be the following:

title = $(event.target).closest('element-row').find('.title');

of course, where the ".descr-button" is bound to the function in the $(document.ready)

$("body").on("click", ".descr-button", do_something);

Related protips:

fatal: refusing to merge unrelated histories

2 Responses
Add your response

Typo. ".closest('element-row')" should be ".closest('.element-row')".

over 1 year ago ·

closest actually exists in native javascript now, and querySelectorAll behaves like find. If you're using jQuery youre probably interested in.siblings( [selector ] )` which is kind of between closest and find.

over 1 year ago ·