开发者

Check if an element doesn't exist and append it

开发者 https://www.devze.com 2023-01-04 14:50 出处:网络
I want select all items that haven\'t an IMG tag and append it. I can do that: How can i do that? <div class=\"test\">

I want select all items that haven't an IMG tag and append it. I can do that:

How can i do that?

  <div class="test">
     <div class="someDummydiv"></div>
  </div>
  <div class="test">
     <div class="someDummydiv"></div>
     <img src="try.gif" />
  </div>
  <div class="test">
     <div class="someDummydiv"></div>
  </div>
  <div class="test">
    <div class="someDummydiv"></div> 
    <img src="try.gif" />
  </div>
  <div class="test">
     <div class="someDummydiv"></div>
  </div>
  <div class="test">
     <div class="someDummydiv"></div>
     <img src="try.gif" />
 </div>

Result -->

  <div class="test">
     <div class="someDummydiv"></div>
     <img src="try.gif" />
  </div>
  <div class="test">
     <div class="someDummydiv"></div>
     <img src="try.gif" />
  </div>
  <div class="test">
     <div class="someDummydiv">开发者_如何学编程</div>
     <img src="try.gif" />
  </div>
  <div class="test">
     <div class="someDummydiv"></div>
     <img src="try.gif" />
  </div>
  <div class="test">
     <div class="someDummydiv"></div>
     <img src="try.gif" />
  </div>
  <div class="test">
     <div class="someDummydiv"></div>
     <img src="try.gif" />
  </div>

Thank you very much


You can use a selector that checks for existence using :not() and :has(), and append to those, like this:

$('.test:not(:has(img))').append('<img src="try.gif" />');

Just replace the selector inside the :not(:has(selector)) to look for what you want to .append().


This should come close:

$('div.test').each(function () {
  var $this = $(this);
  if ($this.children('img').size() == 0) {
    $this.append('<img src=try.gif>');
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消