JQuery every error: Uncaught TypeError: cannot use the "in" operator to search for "18" in the 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" using $ .each

My jQuery

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

it gives an error:

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

http://jsfiddle.net/8xUy3/

+4
source share
3 answers

You need to provide a jQuery collection, not just a selector $.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 is more efficient.

Script example

+16
source

, , , , , .

jQuery, .each():

$("div[data-role=page]").each(function() {
    //...
});

$.each() () .

+9

''

- :

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

Source: https://habr.com/ru/post/1540376/


All Articles