Categories
JavaScript Answers

How to get the first element rather than using [0] in jQuery?

Spread the love

Sometimes, we want to get the first element rather than using [0] in jQuery.

In this article, we’ll look at how to get the first element rather than using [0] in jQuery.

How to get the first element rather than using [0] in jQuery?

To get the first element rather than using [0] in jQuery, we can use the get method.

For instance, we write:

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

to add a few divs.

Then we write:

const el = $('div').get(0) 
console.log(el)

to select all the divs with $.

Then we call get with 0 to return the first one selected.

Therefore, el is the div with text ‘foo’.

Conclusion

To get the first element rather than using [0] in jQuery, we can use the get method.

Leave a Reply

Your email address will not be published. Required fields are marked *