Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery each error :Uncaught TypeError: Cannot use 'in' operator to search for '18' in div[data-role=page]

My html is like

<div data-role="page" id="Dialog_1" data-url="Dialog_1">...</div>
<div data-role="page" id="Dialog_2" data-url="Dialog_2">...</div>
 .
 .
 .
<div data-role="page" id="Dialog_17" data-url="Dialog_17">...</div>
<div data-role="page" id="Dialog_18" data-url="Dialog_18">...</div>

i want to select all data-role="page" by the $.each

My jQuery

$.each("div[data-role=page]", function (){
   console.log($(this).attr('id'));
});

it is giving the error:

Uncaught TypeError: Cannot use 'in' operator to search for '18' in div[data-role=page]

http://jsfiddle.net/8xUy3/

like image 941
Ammar Hayder Khan Avatar asked May 13 '14 13:05

Ammar Hayder Khan


1 Answers

You need to supply a jQuery collection, instead of just a selector to the $.each():

$.each($("div[data-role=page]"), function (){
    console.log(this.id);
});

Or, even better:

$("div[data-role=page]").each(function (){
    console.log(this.id);
});

Please note that I replaced $(this).attr('id') with this.id. It gets exactly the same property, but it's way more efficient.

Fiddle Example

like image 146
Cerbrus Avatar answered Oct 17 '22 01:10

Cerbrus