Juliver Galleto
Juliver Galleto

Reputation: 9037

hide an element base on the specified data attribute

I'm trying to make a filter thing like base on the clicked link text, a div will be hidden base on its data-firstname attribute that match the currently click element but sadly didnt work, below is my snippet. Any clues, ideas, suggestions, help, recommendations would be greatly appreciated, thank you!

$(document).ready(function(){
  $("a").click(function(){
    var thistext = $(this).text();
    //hide all div first
    $("div").hide();
    //show the div that has the match data-firstletter content of the selected link text
    $("div[data-firstletter='" + thistext +"' ]").hide();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">A</a>
<a href="#">B</a>
<a href="#">C</a>

<div data-firstletter="A">
a box that has a data firstletter attribute of A
</div>

<div data-firstletter="A">
a box that has a data firstletter attribute of A
</div>

<div data-firstletter="A">
a box that has a data firstletter attribute of A
</div>

<div data-firstletter="B">
a box that has a data firstletter attribute of B
</div>

<div data-firstletter="B">
a box that has a data firstletter attribute of B
</div>

<div data-firstletter="C">
a box that has a data firstletter attribute of C
</div>

Upvotes: 3

Views: 121

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You're using hide() on both objects - use show() on the elements you select by the data attribute. Try this:

$(document).ready(function() {
  $("a").click(function() {
    var thistext = $(this).text();
    $("div").hide().filter("[data-firstletter='" + thistext + "']").show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="#">A</a>
<a href="#">B</a>
<a href="#">C</a>

<div data-firstletter="A">
  a box that has a data firstletter attribute of A
</div>

<div data-firstletter="A">
  a box that has a data firstletter attribute of A
</div>

<div data-firstletter="A">
  a box that has a data firstletter attribute of A
</div>

<div data-firstletter="B">
  a box that has a data firstletter attribute of B
</div>

<div data-firstletter="B">
  a box that has a data firstletter attribute of B
</div>

<div data-firstletter="C">
  a box that has a data firstletter attribute of C
</div>

Note that I chained the selectors and used filter() to save another query to the DOM.

Upvotes: 4

Related Questions