I’m using JQuery to find certain div classes within DOM & If they found append them inside another div.
Here is working fiddle : http://jsfiddle.net/gTAfe/1/
My code looks something like this :
var parentM = $('#module');
var eltofind = ["heading", "text", "image"];
for(var i=0; i < eltofind.length; i++){
var thisElement = eltofind[i];
if(parentM.find("." + thisElement).length != 0){
var eltoget = parentM.find("." + thisElement);
$(eltoget).each( function(index) {
var count = (index +1);
var getting = thisElement + "-" + count;
$('<div></div>').appendTo('#output').addClass(getting).text(getting);
});
}
}
This script does append but it doesn’t append div in the same order div classes are in the DOM due to each() function. Currently they are appending in the order var eltofind = ["heading", "text", "image"]; are defined.
How do I remember current order of div classes I want to find & append them in the same order within each function ?
Any help would be highly appreciated.
The problem is that you are first finding all
headings, then alltexts and then allimages.So that changes the order. What you need is a multiselector. See: http://api.jquery.com/multiple-selector/
This will find all relevant elements at once and preserve order.
This code snippet works as intended: