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!
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!
Share Improve this question edited Aug 10, 2015 at 11:58 Peter 1,7154 gold badges27 silver badges45 bronze badges asked Aug 10, 2015 at 11:48 MonkeybrainMonkeybrain 8608 silver badges25 bronze badges3 Answers
Reset to default 6A couple of problems there:
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 thejQuery
instance as the first argument and no second argument at all.You're not using
$()
aroundelement
.element
will just be a DOM element, not a jQuery instance, so to calltext
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()); // <===
});
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()
- you are using wrong syntax
$(function(){})
- caching variables makes your script is faster
for
is faster thaneach()
- 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
}