How to chain selectors in jQuery and JavaScript?

Sometimes, we want to chain selectors in jQuery and JavaScript.

In this article, we’ll look at how to chain selectors in jQuery and JavaScript.

How to chain selectors in jQuery and JavaScript?

To chain selectors in jQuery and JavaScript, we can use the find method.

For instance, we write:

<div>
  <p>
    foo
  </p>
  <p>
    bar
  </p>
  <p>
    baz
  </p>
</div>

to add a div with p elements inside.

Then we write:

console.log($('div').find(':last').text())

to select the div with $('div').

Then we call find(':last') to find the last child of the div.

And we call text to get the text content of the last child of the div.

Therefore, we see that 'baz' is logged.

Conclusion

To chain selectors in jQuery and JavaScript, we can use the find method.