Search code examples
javascriptjqueryshow-hide

Hide class element based on ID data of button


HTML

<a class="us-btn-style_6" id="post-102" href="#">Real Estate</span></a>
<article class="w-grid-item post-102" data-id="102"></article>

jQuery function

$('.w-grid-item').hide();
var class1 = ".";
var post_class = "";
$('.us-btn-style_6').click(function(){
    post_class = $(this).data('id')
    post_class = class1 + post_class
    $(post_class).show();
});

There are 7 buttons with 7 corresponding <articles>. The button's ID has the same data as the article's class. What needs to happen, when the button is clicked the <article> needs to be simply show up. In the jQuery I try to take the ID data to show the corresponding class. What goes wrong?


Solution

  • When using the .data method, there should be a corresponding data- prefixed attribute, in this case data-id:

    <a class="us-btn-style_6" data-id="post-102" href="#">Real Estate</a>
    

    Here's a working snippet:

    $('.w-grid-item').hide();
    var class1 = ".";
    var post_class = "";
    $('.us-btn-style_6').click(function(){
        post_class = $(this).data('id')
        post_class = class1 + post_class
        $(post_class).show();
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a class="us-btn-style_6" data-id="post-102" href="#">Real Estate</a>
    <article class="w-grid-item post-102">
    Test
    </article>