If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Review: jQuery collections & looping

jQuery collections

When you use jQuery to find elements, jQuery returns back a jQuery collection object:
var $heading = $('h1');
It is common practice to start variable names like that with a $ sign to show that they're storing jQuery collection objects. That helps distinguish them from variables that store DOM nodes.
If you'd like to retrieve the DOM node out of a jQuery object, then you can treat the jQuery object like an array and use bracket notation:
var heading = $heading[0];
If you'd like to turn a DOM node into a jQuery object, you can pass it into the jQuery function:
var $heading = $(heading);

Looping through collections

If you'd like to loop through multiple elements in a collection, you can use a normal for loop or jQuery's each():
    $("p").each(function(index, element) { 
        $(element).text( $(element).text() + "!!"); 
    });
When you call the each() function, you must pass a 'callback function' to it. jQuery will then call that callback function for each element in the collection, and it will pass the current index and element to the function.
jQuery will also set the context of the function to the current element, which means you can reference the element with the this keyword:
    $("p").each(function() { 
        $(this).text( $(this).text() + "!!"); 
    });

Want to join the conversation?

  • leaf red style avatar for user whitelight
    I don't understand what to do for loopy language??
    (20 votes)
    Default Khan Academy avatar avatar for user
    • leaf orange style avatar for user Bryce
      You want to loop through the p tags (not the individual words) and apply toPigLatin() on them. How you do that is you first loop through the p tags like this:
              var $paragraphs = $("p");
      $paragraphs.each(function(index,element){

      });

      Then you need to make each element into a jquery collection object
      var $paragraph = $(element);
      Then call toPigLatin on each paragraph like this:
              var $paragraphs = $("p");//find all the <p> tags
      $paragraphs.each(function(index,element){//iterates through each paragraph
      var $paragraph = $(element);//turns it into a jquery collection object so .text() will work
      $paragraph.text( toPigLatin($paragraph.text()) );//change the text to pig latin
      });
      (55 votes)
  • female robot ada style avatar for user elanorigby
    For looping through collections, is it necessary to include (index, element) or is that just illustrating the parameters that will get called anyway and you can you just put ()?
    (7 votes)
    Default Khan Academy avatar avatar for user
    • ohnoes default style avatar for user Robert Stone
      You can just use function () and refer to the current element with this. You'd really only need the parameters if you needed to know the index too, and then you'd really only need the first one.

      If a function in JS is defined with parameters and not called with parameters, or called with parameters and not defined with paramaters, they're undefined in the first case or just thrown away in the second case.

      Since this gets bound by jQuery, you can just not use or declare the paramaters.
      (9 votes)
  • blobby green style avatar for user james272
    I wrote the code below but it does not work for last challenge. I cant figure out how and what to pass in to the toPigLatin function. I would really appreciate it if someone could look at code below and figure out what I am doing Wrong.

    $paragraphs = $("p");
    for (var i = 0;i < $paragraphs.length;i++) {
    var element = $paragraphs[i];
    var $paragraph = $(element);
    var $done = toPigLatin $("$paragraph.text");
    $paragraph.text($done.);


    }
    (3 votes)
    Default Khan Academy avatar avatar for user
    • old spice man blue style avatar for user Flostin(READ BIO)
      Instead of doing:
      var element = $paragraphs[i];
      var $paragraph = $(element);

      Just use var element = $($paragraphs[i]);. It's better because you're using less variables, and that's better than using unnecessary variables. Also, you forgot to use the var keyword with $paragraphs = $("p");, so JavaScript won't know what to do with it.

      Also, var $done = toPigLatin $("$paragraph.text"); would cause an error because you're putting a $ in between the function toPigLatin and the parentheses, so the JavaScript (remember, jQuery is used with JavaScript) can't run the function. Second of all, you put $paragraph.text inside quotes, so JavaScript would just treat it as a string, and not run it as code.

      Last of all, $paragraph.text($done.); has one problem, you put $done. inside the parentheses, so JavaScript will think that you're trying to find a values within the Object (in this case: $done.), but you didn't put anything after the dot, so JavaScript won't know what to do, also, you're not even wanting to call from an Object here, well here's the code for the challenge:

      var $paragraphs = $("p");
      for(var i = 0;i < $paragraphs.length;i++) {
      var element = $($paragraphs[i]);
      element.text(toPigLatin(element.text()));
      }


      Good luck and happy coding!
      (10 votes)
  • blobby green style avatar for user Mark G
    The fact that you use TWO diff variables "paragraphs" PLURAL and then " paragraph" SINGLE tripped me up. SO i don't get how the single one knows anything about the plural one?
    (3 votes)
    Default Khan Academy avatar avatar for user
  • aqualine ultimate style avatar for user Karen Y.
    I noticed that in the Looping through jQuery collections video (around ), Pamela used several lines of code to loop:

    var $paragraphs = $("p");
    $paragraphs.each(function(index, element) {
    var $paragraph = $(element);
    $paragraph.html( $paragraph.html() + "..wowee!");
    });


    But in this review page, we're shown that we can use a bit of shorthand:

    $("p").each(function() {
    $(this).text( $(this).text() + "..wowee!");
    });


    (Please correct my code if I made a mistake somewhere!)

    Anyway, my question was: is it better to use more code or less, or does it depend? I can see that it would be much more efficient to use less code, but more self-commenting and human-friendly to use more. And another benefit of naming variables might be to access them more easily if the code is more complex. What are other considerations coders might have?
    (2 votes)
    Default Khan Academy avatar avatar for user
  • winston default style avatar for user Brian W Callaghan
    Loopy Language Challenge. I am not getting it. Need some direction. I am doing this:
    // Iterate through each paragraph, call the toPigLatin function on it
    var $paragraphs = $("p");
    for (i = 0; i < $paragraphs.length; i++) {
    var element = $paragraphs[i];
    toPigLatin("element");

    }
    Nothing happens to the text.
    (1 vote)
    Default Khan Academy avatar avatar for user
    • piceratops tree style avatar for user echen5503
      you can set element back to a jquery collection using
      var paragraph = element;
      Then apply the method to the text using
      paragraph.html(toPigLatin(paragraph.html()));
      this sets the paragraph innerHTML to a piglatinized version, as paragraph.html() is the current html of the element.
      (1 vote)
  • leaf grey style avatar for user Quyen Nguyen
    for Loopy language, I did:
    var $paragraphs = $("p");
    $paragraphs.each(toPigLatin);
    I received a runtime error that str.replace (from the toPigLatin function) was not a function.
    (1 vote)
    Default Khan Academy avatar avatar for user
    • duskpin sapling style avatar for user  DY
      .each() iterates through a jQuery collection. You must pass it a callback function that is written to operate on the context of a DOM node. toPigLatin in it of itself does not modify text of a DOM node, so using it as your callback function does not help you achieve what you want.
      (4 votes)
  • piceratops ultimate style avatar for user Siam Rahman
    How does the toPigLatin function from the last challenge work?

    var toPigLatin = function(str) {
    if (!str.replace) {
    return 'ERROR: Expected a string!';
    }
    return str.replace(/\b(\w)(\w+)\b/g, '$2-$1ay').toLowerCase();
    (1 vote)
    Default Khan Academy avatar avatar for user
    • winston default style avatar for user Bounce888
      The first three lines of the function is an if statement. It checks if str.replace is not existent. Every value can be converted into a Boolean, simply with this logic: if the value is one of (undefined, null, "", NaN, false, 0), then the value is false as a Boolean. If it is not one of those values, then it is true as a Boolean.

      A string value has a replace() method, and a function is not one of those Boolean-falsify values. So, it would return true. But, there's a ! there, which returns the opposite.
      The opposite of true (str.replace) is false.

      If str.replace is oneof the fake values, then it will escape the function with return. Besides giving back a value, return can escape the function.

      The last line calls str.replace(), and passes it a regular expression. Regular expressions are used to perform complex search patterns.
      (3 votes)
  • leaf green style avatar for user khaled.dbl
    can you explain about callback function ..
    (2 votes)
    Default Khan Academy avatar avatar for user
    • piceratops seed style avatar for user alexlightname
      Callback function is normal function is just called later by another function using its passing parameters. Here is visual explanation where method is parameter where its function get callback as *method()* :
              var add = function( a, b, method ){
      if(method){
      var c = method();
      return (a+b)+c;
      }else{
      return a+b;
      }
      }
      add( 2, 3 ); // returns 5
      add( 2, 3, function(){return 7;} ); // returns 12

      now you see similar features in

      $("p").each(function(index, element) { 
      $(element).text( $(element).text() + "!!");
      });

      I know, you would say why they wouldn't name as it is?! less confusion, right! like passing function instead of callback, may be passing would sound funny like passing fart ;)
      (1 vote)
  • starky ultimate style avatar for user Mewlate
    Sorry if this is an obvious question but why is it called DOM nodes?
    (2 votes)
    Default Khan Academy avatar avatar for user