Pull Data-Attribute Value And Hide P Without Matching String

HTML:

<!-- NAV Equivalent -->
<div class="part">
  <a data-type="test">Test</a>
  <a data-type="new">New</a>
</div>

<!-- Items -->    
<div>
  <h5>Example 1</h5>
  <p>Test</p>
</div>

<div>
  <h5>Example 2</h5>
  <p>New</p>
</div>

<!-- Example 3, Test...

jQuery:

$(".part span").click(
  function () {
    var dataType = $(this).attr('data-type');
    $("body").find('p[text*="' + dataType + '"]'):not(:contain("dataType")).addClass("hidden")
  }
);

The way I think/want the jQuery to work:

When a span inside of .part is clicked, take the data-type of that span, and find a paragraph that contains the same string as that data-type's value, and hide any paragraphs that don't contain that string.

jsFiddle: https://jsfiddle.net/CSS_Apprentice/ft5jLka5/2/

Answers 1

  • You've got the right idea, but you are trying to call jQuery selectors as functions.

    Here's a working version.

    $(".part span").click(
      function () {
        var dataType = $(this).attr('data-type');
        $('p:not(:contains("' + dataType + '"))').addClass('hidden')
    
      }
    );
    .hidden{display:none}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="part">
      <span data-type="test">Test</span>
      <span data-type="new">New</span>
    </div>
    
    <!-- Items -->    
    <div>
      <h5>Example 1</h5>
      <p>Test</p>
    </div>
    
    <div>
      <h5>Example 2</h5>
      <p>New</p>
    </div>

    Also, as you mentioned this is a personal dev tool, you can write the string concatenation using javascript ES6 template literals. Much prettier!

    $(`p:not(:contains("${dataType}"))`).addClass('hidden')
    

Related Articles