Search code examples
jqueryfilterhrefeachattr

How to filter articles within a attr href with each and find usage ? simple tag list


I have got lots of div.articles and in that articles; i've got list of tags. I am trying hide article divs which don't got href = '#myFilter'.

I have no problem with reaching to href, my problem is reaching it's parent() without creating jQuery conflict .

Here is jsFiddle example to inspect.

jQuery

//trying to hide which don't got a href '#/news'
var news = '#/news';
$('.article a').each(function() {
    var category = $(this).attr('href');

    if ( category === news ) {//select only articles got #/news href in it
      //$(this).parent().parent().parent().show();//trying to reach article
        $(this).show();
    }else{
      //$(this).parent().parent().parent().hide();//this way hides all articles
        $(this).hide();//this works only on a elements
    }
});​

html:

<div class="article">
    <img src="http://content.photojo.com/content1.jpg" width="50" height="50" />
    <ul>
        <li><a href="#/news">News</a></li>
        <li><a href="#/nature">Nature</a></li>
        <li><a href="#/sport">Sport</a></li>
        <li><a href="#/hobbies">Hobbies</a></li>
    </ul>
</div>
<div class="article">
    <img src="https://encrypt.google.com/content2.jpg" width="50" height="50" />
    <ul>
        <li><a href="#/nature">Nature</a></li>
        <li><a href="#/economy">Economy</a></li>
        <li><a href="#/world">World</a></li>
        <li><a href="#/hobbies">Hobbies</a></li>
    </ul>
</div>

Solution

  • For each of the articles use a closure to track if you should hide the current item. This won't have the flicker of nbrooks' answer.

    As this fiddle shows: http://jsfiddle.net/878zQ/14/

    var news = '#/news';
    var nature = '#/nature';
    var sport = '#/sport';
    var hobbies = '#/hobbies';
    var economy = '#/economy';
    var world = '#/world';
    
    
    $('.article').each(function() {
    
        var hide = 1;
    
        $(this).find('a').each(function() {
    
            var category = $(this).attr('href');
    
            if (category == news) { 
                hide = 0;
            }
        });
    
    
        if (hide == 1) $(this).hide();
    
    });
    

    To explain what this does, here is an english description of the functionality:

    For each page element containing a class of article.
    
        Set the hide flag to true
    
        For each a element in this page element
    
            Look at the href attribute and see if it matches the variable news
            If it does set the hide variable to false.
    
        If the hide flag is true hide this element.