开发者

CSS Selectors - Selecting a specific child element

开发者 https://www.devze.com 2023-02-14 12:20 出处:网络
Here is my code snippet: <div class=\"totals\"> <table id=\"shopping-cart-totals-table\"> <col />

Here is my code snippet:

<div class="totals">
        <table id="shopping-cart-totals-table">
    <col />
    <col width="1" />
    <tfoot>
        <tr>
    <td style="" class="a-right" colspan="1">

        <strong>Grand Total</strong>
    </td>
    <td style="" class="a-right">
        <strong><span class="price">$364.99</span></strong>
    </td>
</tr>
    </tfoot>
    <tbody>

        <tr>
    <td style="" class="a-right" colspan="1">
        Subtotal    </td>
    <td style="" class="a-right">
        <span class="price">$354.99</span>    </td>
</tr>
<tr>
    <td style="" class="a-right" colspan="1">

        Shipping & Handling (Flat Rate - Fixed)    </td>
    <td style="" class="a-right">
        <span class="price">$10.00</span>    </td>
</tr>
    &l开发者_如何转开发t;/tbody>
</table>

Is there a way to select the span displaying "$10.00"? Perhaps selecting the 2nd occurrence of an element? I.E.: The second time ".totals table tbody tr td[colspan='']" occurs?


With CSS3's :nth-child() it's easy to fulfill the "specific" criterion:

#shopping-cart-totals-table > tbody > tr:nth-child(2) > td:nth-child(2) .price

Or, an alternative that works more in favor of browser compatibility (does not use CSS3 selectors, assumes exactly two trs and two tds):

#shopping-cart-totals-table > tbody > tr + tr > td + td .price


If you have the ability to change the output of the shopping cart, you could add a class to the <tr> tag, e.g. <tr class="row01">, <tr class="row02">, etc.

If you can't change your back-end, then it's a choice of front-end tech. The most cross-browser method is to use jQuery to apply the row classes. The other alternative, CSS3, isn't supported by any current IE; given that this is a shopping cart, you're probably interested in the widest level of browser support.

Something like:

$('#shopping-cart-totals-table tr').each(function(n){
    $(this).addClass('row'+n);
});

Alternatively, if you're only interested in the third item, use jQuery in the same way as CSS3:

$('#shopping-cart-totals-table tr:nth-child(2) .price').addClass('highlightClass');
0

精彩评论

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

关注公众号