jQuery .each() with string jQuery .each() with string ajax ajax

jQuery .each() with string


The way you're doing it, you're searching for div elements inside the elements passed in. Basically equivalent of doing a .find().

What you want is filter() which will filter over the top level elements in the collection you passed.

Test it here: http://jsfiddle.net/u5uDg/

var mystring = '<div> bleh content </div> <div> bleh content </div>';$(mystring).filter('div').each(function(e) {    alert('do something');});

If you wanted to use your approach, you would need to give the div elements a parent on which jQuery can perform the find.

http://jsfiddle.net/u5uDg/1/

      // Added parent <div> elementvar mystring = '<div><div> bleh content </div> <div> bleh content </div></div>';$('div', mystring).each(function(e) {  alert('do something');});

As requested in your comment, you can delay execution of the code in the .each() using setTimeout() and arriving at the duration of each by multiplying the current iteration number by the number of milliseconds you want to delay.

http://jsfiddle.net/u5uDg/6/

var mystring = '<div> bleh content </div> <div> bleh content </div>';   // Get the lengthvar length = $(mystring).filter('div').length;$(mystring).filter('div').each(function(e) {    // setTimeout is used to delay code from executing.    // Here we multiply e (which is the index of the current     //   iteration) by 2000 milliseconds, so each iteration    //   is delayed by an additional 2000ms    (function(th) {        setTimeout(function() {                 alert($(th).text());                 if(!--length) { alert('done'); } // alert if done        }, e * 2000);    }(this));});​


Depending on your intent, the jQuery code will look different.

To iterate through divs with content, the divs need not be assigned to a variable in the javascript. They can just live in the html:

<div class="mystring">bleh content</div><div class="mystring">blehhh content</div>

Then, your script will look like the below and you should see the alerts:

$('div.mystring').each(function(e) {  alert('do something');});

If you are trying to iterate through a mystring array, your code would look like this:

var mystring = '<div class="mystring">bleh content</div><div class="mystring">blehhh content</div>';$.each(mystring, function(e) {  alert('do something');});