Check if an element doesn't exist and append it
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>');
}
});
精彩评论