1

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

2 Answers 2

9

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().

Sign up to request clarification or add additional context in comments.

1 Comment

That's really clean. My approach should work as well, and would allow extra processing for elements that don't have images as well, but a one liner is always nice. :)
1

This should come close:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.