wxjljq
Last Updated: January 28, 2017
·
83.73K
· becomingGuru
1d17fab51b9527e3a8f074d52dbddd48

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);

1 Response
Add your response

23366
Default profile 2 normal

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

over 1 year ago ·