开发者

jquery add class if child class has class xxx

Trying to add a class to a font tag with class "pricecolor" if child has a class of "PageText_L657n".

    <table width="100%" cellspacing="0" cellpadding="0">
  <tbody>
    <tr>
      <td width="64%" valign="top"> Stock Item (Usually Ships Within 24 Hours) <br>
        <font class="text colors_text"><span class="PageText_L483n"><b><span class="PageText_L334n">MSRP</span>: $4,895.00</b> </span></font><br>
        <b><font class="pricecolor colors_productprice"><span class="PageText_L483n"><font class="text colors_text"><b>Regular Price: </b></font> $1,872.34 </span></font></b><br>
        <br>
      <a class="pricecolor colors_productprice"><span class="PageText_L657n"><span style="font-size: 16px; color: rgb(0, 0, 255);">Click To Get Today's Special Price!</span></a></td>
      &开发者_Python百科lt;td width="36%" align="right"></td>
    </tr>
  </tbody>
</table>

<script>
$(function(){
$(".pricecolor").child().hasClass("PageText_L657n").addClass("ice1");
});

</script>


Use the :has() selector:

$('.pricecolor:has(.PageText_L657n)').addClass('ice1');


EDIT: After clarification, it seems you want this:

Example: http://jsfiddle.net/WeCCT/2/

$('.PageText_L657n').closest('td').find('.pricecolor').eq(0).addClass('ice1');

This selects elements with the class PageText_L657n, then gets its nearest ancestor <td> and uses the find()(docs) method to locate nested .pricecolor elements, and the eq()(docs) method to narrow it down to the first before adding the class.


Original answer

If you want to limit yourself to valid querySelectorAll selectors, do this:

$('.PageText_L657n').parent('.pricecolor').addClass('ice1');

This starts with selecting the .PageText_L657n element, then traverses up to its parent and only adds the class if the parent has the .pricecolor class.


The .pageText classes are only in the markup when you are an administrator for that site. Your store will not render your css code on the frontend when you are not logged in because those classes do not exist in the source anymore. I had the same problem since I was always coding while I was logged in to the site.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜