Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

javascript - Select all images without a specific parent class

I need to select the second image inside of a div (.entry-content) unless the image has a specific parent class. Here is an example of my attempts

In the example below, I would need to select the third image since the second image has the parent class of parent-div.

jQuery(".entry-content").each(function() {
  jQuery(this).find("img:eq(1):not(:parent.parent-div)").addClass("second-img");
});
// or 
jQuery(".entry-content").each(function() {
  jQuery(this).find("img:eq(1)").not().parent(".parent-div").addClass("second-img");
});
.second-img { border: 1px solid black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="entry-content">
  <p></p>
  <p></p>
  <p><img /></p>
  <div class="parent-div"><img /></div>
  <div><img /></div>
  <div></div>
  <div class="parent-div"><img /></div>
  <p></p>
  <img />
  <img />
  <p></p>
  <p><img /></p>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you can use below script to find the correct image element. You can use filter to filter image element not having parent-div class for parent. See below script for reference

$(function() {
  var found = false;
  var $img = $('div.entry-content img:gt(1)').filter(function() {
    if (!found) {
      var $parent = $(this).parent();
      if(!$parent.hasClass('parent-div')) {
        found = true;
        return true;
      }
    }
    return false;
  });
  $img.each(function() {
    console.log($(this).attr('src'));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="entry-content">
  <p></p>
  <p></p>
  <p><img src="1" /></p>
  <div class="parent-div"><img src="2" /></div>
  <div><img src="3" /></div>
  <div></div>
  <div class="parent-div"><img src="4" /></div>
  <p></p>
  <img src="5" />
  <img src="6" />
  <p></p>
  <p><img src="7" /></p>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...