Search code examples
jqueryregexparent

jQuery: test regex pattern of class


Heyho,

I'd like to adress the parent elements of different paragraphs. Cause the paragraphs are nested in a different way I cannot adress the same way by using "closest" or sth..

That's why I try to use regex testing to adress #text-test AND #img-test:

<div class="text-test">
    <p class"tester">texttest</p>
</div>
<div class="img-test">
   <div class="wrapper">
    <p class="tester">imgtest</p>  
   </div>
</div>

$('.tester').click(function() {
    //$(this).closest('div').addClass('active');
    /* get the closest div where the class ends up with -test
    * and add class active 
    * wrapperdiv = $(this).closest('div').attr('class').test(/-test$/);
    */
    //console.log(wrapperdiv)
});

Do you have an advice how I could adress by using the test-method?

Cheers


Solution

  • $(this).closest('div[class$="-test"]').addClass('active');
    

    [name$=value] called End with selector. For above case, which will select those div, whose class end with -test.