Home >Web Front-end >CSS Tutorial >How Can I Select DOM Elements Based on the State of Another Element Using CSS Selectors?

How Can I Select DOM Elements Based on the State of Another Element Using CSS Selectors?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 13:18:25668browse

How Can I Select DOM Elements Based on the State of Another Element Using CSS Selectors?

Selecting Elements Based on State Relationships in CSS

Problem: Select other elements in the DOM based on a specified state of an element.

Conditions for Selecting:

  • Represent states using simple selectors (e.g., div, [data-status~=finished]).
  • Express structural relationships using combinators to form a complex selector.
  • Make the targeted element the subject of the complex selector.

Current Limitations:

Unfortunately, these conditions cannot all be met using current CSS Selectors, due to:

  • Lack of a parent selector (to target an ancestor of the subject element)
  • Lack of a previous sibling selector (to target siblings that come before the subject element)

Upcoming Capabilities:

The upcoming CSS Selectors 4 standard introduces features that address these limitations:

  • :matches() pseudo-class: Groups multiple compound selectors.
  • :has() pseudo-class: Selects elements that contain child elements matching a selector.

Solving the Example Problem:

Using :has() and :matches(), we can solve the example problem in CSS Selectors 4:

section:has(> div[data-status~=finished]) + section > div:matches(.blink, .spin) {
  /* styles for targeted elements */
}

Alternative Approach with JavaScript:

While these features are not yet supported by all browsers, you can currently use JavaScript to select elements using :has():

$('section:has(> div[data-status~=finished]) + section > div').filter('.blink, .spin').css('color', 'red');

The above is the detailed content of How Can I Select DOM Elements Based on the State of Another Element Using CSS Selectors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn