tags:

views:

54

answers:

2

This is a jQuery example. But i didn't get the part below:

var replacement = $("<li>").text($(this).text()).get(0); 

The original code:

var mappedItems = $("li").map(function (index) {
  var replacement = $("<li>").text($(this).text()).get(0);
  if (index == 0) {
    // make the first item all caps
    $(replacement).text($(replacement).text().toUpperCase());
  } else if (index == 1 || index == 3) {
    // delete the second and fourth items
    replacement = null;
  } else if (index == 2) {
    // make two of the third item and add some text
    replacement = [replacement,$("<li>").get(0)];
    $(replacement[0]).append("<b> - A</b>");
    $(replacement[1]).append("Extra <b> - B</b>");
  }
  // replacement will be an dom element, null, 
  // or an array of dom elements
  return replacement;
});
$("#results").append(mappedItems);

Any comments?

+2  A: 

The jQuery methods usually return the jQuery object, so that they can be chained. So, the expression does the same as:

var x = $("<li>");
x.text($(this).text());
var replacement = x.get(0);

It creates a new li element that is wrapped in a jQuery object, sets the text of the element, and then gets the element itself from the jQuery object.

Guffa
why use get(0) ? what would happen if it was get(1) or get(n)?
yakup
@yakup85: The `get(0)` call gets the first element in the jQuery object, which happens to be the only one there is in this case. If you use a different index you will get an undefined value.
Guffa
thanks. now i get it.
yakup
+1  A: 

Also worth to mention, .get() returns a DOM element. Since jQuery objects are stored in arrays ("array like objects"), you could also access the underlying DOM element by calling

var replacement = $('<li>')[0];
jAndy