Calling .each on one element

289 Views Asked by At

I'm using node.io to scrape websites. Currently I'm going through the scraping tutorial.

I'm using each with a selector

$('selector').each( ... , function () { ... } );

However when the selector selects only one element, I am receiving this problem:

TypeError: Object #<Object> has no method 'each'

What might be a cause for this, and how can I mitigate this issue

2

There are 2 best solutions below

13
On BEST ANSWER

After looking at node.io's source code, it appears that by default it uses node-soupselect and not jQuery.

Try setting:

this.options.expand_single_selected = false;

inside your job's run method. Alternatively, when you create the job, set it

new nodeio.Job({timeout:10,expand_single_selected:false}, methods);

This is checked by these lines in the code, and it will enforce the correct behavior.

From node.io's creator chriso:

To be honest, this is a design fail on my part. I was sick of typing first() every time I wanted a single element from a collection with only one item, so I added this shortcut - I knew it would come back to bite me at some stage!

See this project issue on how you could change it to use jQuery instead which will solve your issue, along with workarounds and benefits of sticking to soupselect.


According to your link, when you're using $ you're not using jQuery, you're using node-soupselect.

It does not have a .each method.

Instead use

$('selector').forEach

Which is a native JS function

0
On

If you put your single element in [brackets] it will act as a single item array and get rid of this problem