What's the difference between a jQuery object and a DOM element? Difference between .get() and .index()?

后端 未结 7 1008
慢半拍i
慢半拍i 2020-12-03 12:16

I\'m lead to this question when trying to figure out the difference between jQuery\'s .get() and .index(), I\'ve looked over the jQuery API and I s

7条回答
  •  情话喂你
    2020-12-03 12:42

    One way I liked to look at it when I was starting out with jQuery is something like this (and yeah, I know everything's not entirely correct, but they worked as loose analogies):

    DOM elements are the nodes in your HTML document that you normally get with vanilla Javascript. Something like var foo = document.getElementById('bar') gets you a raw DOM element.

    jQuery wrapper objects (for a big part of jQuery development) is basically a whole new object that contains a DOM element. And that's basically it, a container. This is what you get with something like $('#bar') and that's what you get as well by chucking in a DOM element like $(foo). These enable the various jQuery functionalities on your DOM objects --- stuff they normally wouldn't have if they were plain DOM objects.

    Building on that, the difference between .get() and .index() is pretty easy.

    .get(n) returns the nth DOM element in a jQuery wrapper object. Something like $('input').get(0) gives you the first element in the DOM as if you called document.getElementById() on it (or something similar). .eq(n) does something similar, but returns a jQuery wrapper object containing the DOM element instead.

    .index() just gives you what position a particular element is in a jQuery wrapper object. This works a lot like how you'd expect them to work in arrays and other collections.

提交回复
热议问题