Jqueryのfilter関数を使って特定の子要素の場合に処理を実行するコードです。filter関数はif分岐と似たような感じで使えますが、メソッドチェーン出来るという点があります。
今回はimgタグがaタグの中にあった場合にaタグにクラスを付与するという簡単なコードです。
html
<div id="context" class="context"> <div class="hogeho"><a href="#"><img src="img.png" width="300" height="300"></a></div> <p><a href="#">テキスト</a></p> </div>
css
.context {} .context a{ padding-bottom: 5px; border-bottom: 1px dotted #222; } .context a.style1{ padding-bottom: 0; border-bottom: none; }
Jquery
$(function(){ var obj = $(".context a"); obj.each(function() { $(this).filter(function(){ return $(this).find("img").length > 0 //ここで特定の子要素の判定 }).addClass("style1"); }); });