You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS选择器顺序影响结果:调换tr属性后无法获取预期<a>标签?

Fixing the jQuery Selector Order Issue

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:

  1. All <tr> elements with a bgcolor attribute inside your target table
  2. All <a> elements inside <td align="left"> that are within <tr> elements with a style attribute (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:

  1. All <tr> elements with a style attribute inside your target table
  2. All <a> elements inside <td align="left"> that are within <tr> elements with a bgcolor attribute (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:35:55