Skip to content Skip to sidebar Skip to footer

Hide All But First Matching Element

I am using jquery to sort through multiple paragraphs. Currently I have it set to show only paragraphs that start with a current letter. But now, I would like to consolidate furt

Solution 1:

OK, I think I understand now.

Try this:http://jsfiddle.net/Upa3S/

var letter = 'B';

    vararray = [];  // Stores array of the content of paragraphsfunctionfinish(){
        jQuery('p').each(function(){

               // Cache reference to the paragraph$th = jQuery(this);
            if($th.text().substr(0,1).toUpperCase() == letter) {

                    // Test if we've already stored the current content in arrayif(jQuery.inArray($th.text(), array) > -1) {
                       // If so, hide it$th.addClass('hidden'); // You can do $th.hide() if you prefer
                } else {
                       // If not, put its content in the array$th.addClass('current-series');
                    array.push($th.text());
                }
            } else {
                $th.hide();
            }
       })
    }

finish();​

Or using .filter()

http://jsfiddle.net/Fjj5d/

var letter = 'B';

vararray = [];

functionfinish(){
    jQuery('p').filter(function(){
        $th = jQuery(this);
        if($th.text().substr(0,1).toUpperCase() == letter && jQuery.inArray($th.text(), array) < 0 ) {
            array.push($th.text());
            $th.addClass('current-series');
        } else {
            return this;
        }
    }).hide();
}
finish();

Solution 2:

This will hide all but the first paragraph with that first letter:

EDIT: You can do the following messy solution.

function finish(){
    var found_first = [];
    jQuery('p').each(function(){     
    if(jQuery(this).text().substr(0,1).toUpperCase() == letter){
    if(found_first[jQuery(this).text()] != true){
        jQuery(this).addClass('current-series');
        found_first[jQuery(this).text()] = true;
    }else{
        jQuery(this).hide();
    }
    }
    else{ jQuery(this).hide();}
   })

}

Post a Comment for "Hide All But First Matching Element"