简体   繁体   English

jQuery .closest找不到正确的p元素

[英]jQuery .closest not locating correct p element

I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward. 我试图确定为什么我的某些代码无法正常工作,即使看起来很简单。

As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest p element (which is the element that houses the img element) b and add that the class CM-blog-image . 如下所示,我确定img标签包含size-full类,然后打算找到最接近的p元素(即存放img元素的元素)b并添加该类CM-blog-image Why isn't this working? 为什么这不起作用?

if($('.entry-content p img').hasClass('size-full')) {

        $(this).closest('p').addClass('CM-blog-image');
}

HTML HTML

<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>

You can simply use like this: 您可以像这样简单地使用:

$('.entry-content img.size-full').parent().addClass('CM-blog-image');
               //or you may use   ^^ closest('p')

You can achieve it using simple traversal methods. 您可以使用简单的遍历方法来实现。 No need to use .each() 无需使用.each()

$('.entry-content p img.size-full') //Find image with the class
     .closest('p') //Traverse up to paragraph element
     .addClass('CM-blog-image');  //Add the required class

I assume you want to add class to each element found. 我假设您想将类添加到找到的每个元素中。

$('.entry-content p img').each(function(){
    if($(this).hasClass('size-full'))
        $(this).closest('p').addClass('CM-blog-image');
});

If you have p tag and image tag immediate next of entry-content class. 如果您在条目内容类的下一个紧接有p标签和image标签。 Use like below. 如下使用。 it should work. 它应该工作。

if($('.entry-content > p > img').hasClass('size-full')) {

        $(this).closest('p').addClass('CM-blog-image');
}
//select img with class size-full
 var elm = $('.entry-content p img.size-full');

  // add CM-blog-image to closest parent p
 elm.closest('p').addClass('CM-blog-image');

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

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