如果图像父级没有某个类,则jQuery在div中选择图像

Ale*_*lex 2 jquery-selectors

Wordpress使用.wp-caption类在div中包含带字幕的图像.我正在寻找一种方法来选择没有这个div的图像,所以我可以将它们包装在不同的div中.(在所有图像周围保持一致的边框)

<div class="blog-post-content"> 
 <div id="attachment_220" class="wp-caption alignleft" style="width: 310px">
  <a href="/somewhere/"><img class="size-medium wp-image-220" src="/path/to/image" alt="" width="300" height="280" /></a>
  <p class="wp-caption-text">Caption Text</p>
 </div>
 <p>This is the body of the post</p>
</div>
Run Code Online (Sandbox Code Playgroud)

要测试我的选择器,我只是想添加一个绿色边框.一旦选择器工作,我可以处理.wrap().

我最有希望的尝试是:

$('.blog-post-content img').parent('div:not(".wp-caption")').css('border', '2px solid green');
Run Code Online (Sandbox Code Playgroud)

......但没有运气.

Joh*_*lum 5

怎么样:(未经测试)

$('.blog-post-content img').filter(function(){
    return !$(this).parents('div').hasClass('wp-caption');
}).css('border', '2px solid green');
Run Code Online (Sandbox Code Playgroud)

  • 你需要parent()而不是parent(),因为在img和div之间似乎有一个额外的元素(a).否则似乎很好.编辑:事实上你可以使用return!$(this).parents('div.wp-caption').length;,但那只是挑剔. (2认同)