Search code examples
javascriptjqueryhtmlfindpartial

How to execute partial find on dynamic HTML5 data descriptor?


I have a series of images tagged with HTML5 data descriptor "data-type2=[x]" where x is a number of different elements.

e.g.

    <img data-type2="pants" class="element" src="#>

I am trying to pass that data field into a jquery function that finds classes in another div (<div class="outfit-list") that has child divs tagged with classes such as:

    <div class="pants-001">
    <div class="pants-002">
    <div class="shoes-001">

etc.

Here is where I am stumped: how do I write a jquery function that accesses data type2 from the item I click (e.g. data-type2="pants"), finds all other divs under .outfit-list with classes that have, for example, "pants" in their class name "pants-002", and hide them? The function I have below does not work - I suspect that's because it's looking for the full name and not partial.

How do I make it perform a partial search to locate the classes that contain the term from data-type2?

        <script type="text/javascript">
            $(document).ready(function(){
             $('.thumbslist .element').click(function(){
                $('.outfit-list').find('.'+$(this).data('type2')).hide();
              });
            }); 
        </script>   

Solution

  • You can use the attribute contains selector, [attribute*="value"].

    $('.outfit-list').find('[class*="' + $(this).data('type2') + '"]').hide();