1

I am showing articles in a list of divs. Each div has a data attribute that contains the status of the article.

<div id="article_1" data-status="read"> ... </div>
<div id="article_2" data-status="unread"> ... </div>

There is a button that toggles views to show "All Articles" or only "Unread" articles.

My toggle function looks like this, which is working fine:

function toggle(status) {
    if (status == 'all') {
         $('*').filter(function() {
            if ($(this).data('status') == "read") {
                $(this)[0].style.display = 'block';
            }
         });  
    }
    else {
         $('*').filter(function() {
            if ($(this).data('status') == "read") {
                $(this)[0].style.display = 'none';
            }
         });
    }
}

Question: Is there a better (faster, efficient) way to select divs with data-status attribute and based on the status toggle the view?

Ref:

[1] Jquery select all elements that have $jquery.data()

[2] Show/hide multiple divs based on a value in their attribute

[3] filtering divs in jQuery and hiding them based on a custom data attribute tag

Community
  • 1
  • 1
The Wanderer
  • 3,051
  • 6
  • 29
  • 53

2 Answers2

4

You can just select on the data-status attribute itself:

function toggle(status) {
    if (status == 'all') {
      $('[data-status=read]').css('display', 'block');
    }
    else {
      $('[data-status=read]').css('display', 'none');
    }
}

toggle('unread');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="article_1" data-status="read"> read </div>
<div id="article_2" data-status="unread"> unread </div>
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
1

I think you can go very simple here:

function toggle(status) {
  if (status == 'all') {
    $('*[data-status="read"]').show();
  } else {
    $('*[data-status="read"]').hide();
  }
}

Hope that helps

Guido Kitzing
  • 892
  • 5
  • 14