Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS selectors for excluding by attribute presence

The document I am parsing has the following two styles of td tags (among other instances of td tags):

<td align="right" nowrap bgcolor="#A1C87A">...</td>

<td align="right" nowrap>...</td>

How do I write a selector which only selects the second type, and exclude all the other td tags?

document.css('td:not([bgcolor="#A1C87A"])')

excludes the first type, includes the second type plus all other td tags as well.

document.css('td[align="right"][nowrap]')

excludes all other td tags, but includes both types above.

like image 912
Prakash Murthy Avatar asked Jan 01 '15 19:01

Prakash Murthy


People also ask

How do I exclude a selector in CSS?

In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector. Since it is used to prevent a specific items from list of selected items.

How do you target an element with an attribute in CSS?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

How do you create a CSS rule for all elements except one class?

Approach: Use the :not(selector), also known as negation pseudo-class which takes a simple selector as an argument and allows you to style all the elements except the element specified by the selector.


1 Answers

You can simply combine the :not selector with the other attribute selectors:

document.css('td:not([bgcolor="#A1C87A"])[align="right"][nowrap]')

You could even put the :not after the others (it doesn’t need to be right next to the element name):

document.css('td[align="right"][nowrap]:not([bgcolor="#A1C87A"])')

These will both select all td elements that have bgcolor="#A1C87A" and nowrap but don’t have align="right", which is what you’re after.

like image 88
matt Avatar answered Oct 29 '22 01:10

matt