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

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect !! Plain and simple. Thank you.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.