简体   繁体   English

选择通配符子类并将类添加到父级

[英]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. 我想选择aimg的父class它的classblah-3-**是一个通配符,因为它可以是任何数字。 Then I want to add the class gallery to the a parent. 然后我想添加类gallerya父。

<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. 因此,在执行代码之后, a href应该添加class="gallery"

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. 谢谢。

Fix Quotes and brackets. 修复报价和括号。 You need wildcard selector * instead of startswith selector ^ 您需要通配符选择器*而不是startswith选择器^

$('.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. 如果你的a有其他类,你也可以使用.addClass。 If the class is already present .addClass won't add it again. 如果该类已经存在.addClass将不再添加它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM