Monkeybrain
Monkeybrain

Reputation: 860

Element undefined in jQuery each iteration

I'm trying to iterate over a collection of jQuery elements as follows:

var l = $(".ace_line").length;
$(".ace_line").each($(function(index,element) {
    console.log("Element = " + element);
    console.log(index + ": " + element.text());
}));

When I examine l its value is 39 so I know the collection is not null. However element is undefined when I loop through the collection.

What am I doing wrong?

Any help would be appreciated!

Upvotes: 1

Views: 2481

Answers (3)

oshell
oshell

Reputation: 9123

  • you are using wrong syntax $(function(){})
  • caching variables makes your script is faster
  • for is faster than each()
  • by using for you do not have to wrap your element with $() again

jQuery

var lines = $(".ace_line"); //caching the element
var l = lines.length; //getting length for loop without selecting element again
for (var j = 0; j < l; j++){ //for loop where j is your index
    console.log(lines.eq(j)); //getting the element by using jQuery's eq()
    console.log(lines.eq(j).text()); //use any jQuery function on the element
}

Upvotes: 0

Peter
Peter

Reputation: 1715

Remove the $( from within the each function, like so:

var l = $(".ace_line").length;
$(".ace_line").each(function(index,element) {
    console.log("Element = " + element);
    console.log(index + ": " + $(element).text());
});

Additionally, your element will be a HTML DOM element, not a jQuery item, so to get .text() you would need $(element).text()

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075755

A couple of problems there:

  1. You're wrapping your callback in $(), which makes jQuery think you're using the shorthand version of $(document).ready(function...). Since the DOM is ready, it calls that function (once) passing it the jQuery instance as the first argument and no second argument at all.

  2. You're not using $() around element. element will just be a DOM element, not a jQuery instance, so to call text on it, you need to wrap it first.

So:

var l = $(".ace_line").length;
$(".ace_line").each(function(index,element) {
// No $( here ------^
    var $el = $(element);                     // <=== Do wrap `element`
    console.log("Element = " + $el);
    console.log(index + ": " + $el.text());   // <=== Use $el
}); // <== Removed a ) here

Note that the more normal thing to do would be to use this:

var l = $(".ace_line").length;
$(".ace_line").each(function(index) {
    var $el = $(this);                        // <===
    console.log("Element = " + $el);
    console.log(index + ": " + $el.text());   // <===
});

Upvotes: 6

Related Questions