0

Now I learning Backbone and Marionette, I read some tutorial and I found a code whom I haven't understand. Here's the code:

$('element',this.el)[0]

I know jQuery little bit. I know this keyword, i know the $('element') keyword, but not understand that code, please everybody tell me about that.

Engkus Kusnadi
  • 2,386
  • 2
  • 18
  • 40

3 Answers3

5

This $('element',this.el) says select all <element> contained within this.el. this.el must be another "object" but what it is depends on what is building this higher up. I cover this in more detail in this answer to a similar question.


The [0] simply unwraps the jquery object returning a vanilla DOM object. So:

$('element',this.el).first(); //works
$('element',this.el)[0].first(); //will error

The second errors becuase it is no longer a jquery object so it is not wrapped in the jquery functions.

Community
  • 1
  • 1
Liam
  • 27,717
  • 28
  • 128
  • 190
  • So can I say that code is "select first element which has name `element` in `this.el` element" ? – Engkus Kusnadi Aug 04 '16 at 08:21
  • almost: "select first element which **of the type** element in this.el **and then unwrap the jquery object from around it**" – Liam Aug 04 '16 at 08:22
  • I do not understand a bit of what you are talking about, can you add an simple diagram image or something like that so I can fast understand what are you saying? – Engkus Kusnadi Aug 04 '16 at 08:29
  • I owuld suggest you have a look though the [jquery learning docs](http://learn.jquery.com/). I don't think I can simplify it anymore than I can. This is very basic jquery – Liam Aug 04 '16 at 08:34
2
  • In Backbone context, your code is probably found inside a view and this.el refers to the view's element
  • $('element',this.el) find the element nodes inside the scope defined by this.el
  • $('element',this.el)[0] refers to the first element node found

Note that in a Backbone view, you can simplify to

this.$('element')[0]
nikoshr
  • 32,926
  • 33
  • 91
  • 105
0

This is the jquery selector context syntax:

'element' is to a selector and this.el is a context and using bracket notation to get the first element [0] which also converts jquery element to javascript object.

Alternatively you can use like this instead of jquery selector context syntax:

$(this.el).find('element')[0] // hope you understand this syntax
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231