CSS选择器顺序影响结果:调换tr属性后无法获取预期<a>标签?
The problem here boils down to how CSS (and jQuery) handles comma-separated selectors—each part split by a comma acts as a completely independent selector.
In your original query:
$('.wikitable.sortable.plainrowheaders tr[bgcolor],tr[style] td[align=left] a')
This actually selects two separate sets of elements:
- All
<tr>elements with abgcolorattribute inside your target table - All
<a>elements inside<td align="left">that are within<tr>elements with astyleattribute (anywhere on the page, not just your table)
When you reversed the order:
$('.wikitable.sortable.plainrowheaders tr[style],tr[bgcolor] td[align=left] a')
It selects:
- All
<tr>elements with astyleattribute inside your target table - All
<a>elements inside<td align="left">that are within<tr>elements with abgcolorattribute (anywhere on the page)
The reason you're seeing <tr> elements in the reversed case is because the first part of the selector now returns those <tr style> elements from your table. In the original, maybe there were no matching <tr bgcolor> elements in the table, so you only noticed the <a> tags from the second part.
To fix this so both orders (and any order) return only the <a> tags you want, you need to ensure both parts of the selector target <a> elements inside the correct <tr>s within your table. Here are a few clean, reliable ways to do this:
Option 1: Explicitly scope both selectors to the table
$('.wikitable.sortable.plainrowheaders tr[bgcolor] td[align=left] a, .wikitable.sortable.plainrowheaders tr[style] td[align=left] a')
This makes sure both parts of the selector are looking for <a> tags inside the respective <tr>s within your target table, no extra elements included.
Option 2: Use jQuery's find() for cleaner syntax
$('.wikitable.sortable.plainrowheaders') .find('tr[bgcolor], tr[style]') .find('td[align=left] a')
First we target the table, then grab all relevant <tr>s, then drill down to the exact <a> tags you need. This avoids repeating the table class selector and is easier to read at a glance.
Option 3: Combine tr attribute checks in one chain
If you prefer a more condensed single-line approach:
$('.wikitable.sortable.plainrowheaders tr[bgcolor], .wikitable.sortable.plainrowheaders tr[style]').find('td[align=left] a')
This works the same way as option 2 but wraps the tr selection into the initial selector.
Any of these approaches will consistently return only the <a> tags you're targeting, regardless of the order you list the <tr> attributes.
内容的提问来源于stack exchange,提问作者Madhur

