2009-11-12

Using jQuery: Looping an array of objects misstake

I recently spent some time to get some jQuery code to work, but I just couldn't. After a while I realised my mistake and thought this would make a great blog post (mostly so I'll remember this myself).

The task was to find out how many paragraphs contained a certain text. For the purpose of this example lets say "xxx".

Here is the
jQuery I started out with (sorry about missing the indenting):

$(document).ready(function()
{
var pArray= $("p");

for(var i = 0; i <
pArray.length; i++)
{
if(
pArray[i].text().indexOf("xxx") != -1)
{
// Do something...
}
}
});


This crashed since
text() wasn't a function. Strange since it's in the jQury reference. I got it to work with textContent() instead but not in IE. After a while I realised my mistake. The pArray[i] is not a jQuery object, so adding $() did the trick. This was the result:

$(document).ready(function()
{
var
pArray= $("p");

for(var i = 0; i <
pArray.length; i++)
{
if($(
pArray[i]).text().indexOf("xxx") != -1)
{
// Do something...
}
}
});


Now don't forget this!

But wait! Sometimes you have to stop and think what you are doing. jQuery is more powerful than you think. Consider the following code, which accomplishes the same thing:

$("p:contains(xxx)")

Reminder to self: always stop and think and read the spec...

No comments: