AAA
AAA

Reputation: 2032

Selecting wildcard child class and adding class to parent

I want to select the a that is the parent of the img whose class has blah-3-* with * being a wildcard since it could be any number. Then I want to add the class gallery to the a parent.

<div class="content">
    <a href="link">
        <img src="blah.jpg" class="blah-1 blah-2 blah-3-01">
    </a>
</div>

So after the code is executed, the a href should have class="gallery" added to it.

This is my nonworking code:

$('.content a > img[class^='blah-3'').parent().attr('class', 'gallery');

Code doesn't work, and it gives me an unexpected identifier error.

What is wrong with my code? Could someone please educate me?

Thanks.

Upvotes: 0

Views: 281

Answers (1)

PSL
PSL

Reputation: 123739

Fix Quotes and brackets. You need wildcard selector * instead of startswith selector ^

$('.content a > img[class*=blah-3]').parent().attr('class', 'gallery');

or

$('.content a > img[class*=blah-3]').closest('a').attr('class', 'gallery');

You can also use .addClass if your a has other classes. If the class is already present .addClass won't add it again.

$('.content a > img[class*=blah-3]').closest('a').addClass('gallery');

Upvotes: 2

Related Questions