HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Optimize jQuery Iteration

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
iterationjqueryoptimize

Problem

I have a list of elements (well, nested lists of elements, really) that the user can reorder (using jQuery sortable()). A simplified view of the structure is something like:


    
    
        
            
            
            
        
        
            
            
            
        
    
    
        
            
            
            
        
        
            
            
            
        
    
    


Each .content inside of .contentList is sortable, and each .triggerContent inside of .contentListInner is also sortable (independently of the other sections). Each element within these sections is numbered according to its position in its own list. So to continue with the example above, the correct numbering is:


     
       
        
             
             
             
        
        
             
             
             
        
    
     
        
             
             
             
        
        
             
             
             
        
     
     


There's an additional complication, in that each .triggerContent can contain a new repetition of the entire structure, beginning again from .contentList. This nested content, however, is essentially spurious and should be ignored for all practical purposes.

Anyhow, to apply the numbering to the inner sections (and simultaneously ignore content in the aforementioned nested sections), I'm currently using the following code:

$(".contentListInner").each(function() {
    var taskNum = 1;
    $(this).find(".triggerContent .taskTitle .left .number").each(function() {
        if ($(this).parents(".triggerContent").length == 1) {
            //FIXME:  filtering on parents() is *slow*; find a faster approach
            $(this).text("Task " + taskNum);
            taskNum++;
        }
    });
});


This works, but as the FIXME notes I found that filtering using .parents() is incredibly slow. If I don't filter on `.p

Solution

Try using the children selector: http://api.jquery.com/children/.

This only retrieves the first set of nested items (one level down vs. find which goes all the way down). I'm not sure how you're nested exactly with your other classes, but it would be something like this.

$(".contentListInner").each(function() {
    $(this).children(".triggerContent").each(function(index, element) {
       $(element).text("Task " + (index + 1));
    });
});

Code Snippets

$(".contentListInner").each(function() {
    $(this).children(".triggerContent").each(function(index, element) {
       $(element).text("Task " + (index + 1));
    });
});

Context

StackExchange Code Review Q#22881, answer score: 4

Revisions (0)

No revisions yet.