Search code examples
jqueryappendto

How do i make my jQuery more specific?


I am trying to use a function only once instead of writing it for every block of UL LI's that i need to convert to select lists. My working code is on http://jsfiddle.net/qqzB5/

I tried this but it will loop over ALL the li's, not just the one within the specific section:

$('.filterSection').each(function(){

        $('<select class="locationFilterSelect" />').appendTo(this);
        //Create Default option "Select One"
        $("<option />", {
           "selected": "selected",
           "value"   : "",
           "text"    : "Select One"
        }).appendTo('select', this);
        // Populate dropdown with menu items
        $('li', this).each(function() {
             var el = $(this);
             $("<option />", {
                 "text"    : el.text()
             }).appendTo('select', this);
        });
    });

Solution

  • You messed up with .appendTo. It takes one argument, doesn't it? And you need to use some scoping: pass select variable from outer handler to inner handler. Look at this code:

    $('.filterSection').each(function(){
        var select = $('<select class="locationFilterSelect" />')
        select.appendTo(this);
        //Create Default option "Select One"
        $("<option />", {
           "selected": "selected",
           "value"   : "",
           "text"    : "Select One"
        }).appendTo(select);
        // Populate dropdown with menu items
    
        $(this).find('li').each(function() {
             var el = $(this);
             $("<option />", {
                 "text"    : el.text()
             }).appendTo(select);
        });
    });