Home >Backend Development >PHP Tutorial >How Can I Accurately Select CSS Classes Using XPath?

How Can I Accurately Select CSS Classes Using XPath?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-06 04:35:11778browse

How Can I Accurately Select CSS Classes Using XPath?

Selecting CSS Classes with XPath: A Comprehensive Guide

The Challenge

Selecting CSS classes with XPath poses a unique challenge as XPath lacks a native equivalent to the CSS class selector. This article explores the intricacies of this issue and provides an efficient solution.

The Wrong Way: Class Equal to

XPath selectors using //*[@class="foo"] fail to select elements with multiple classes or whitespace around the class name.

The Wrong Way: Class Contains

Selectors like //*[contains(@class, "foo")] match elements with classes such as foobar, which is incorrect.

The Right Way: Normalize-Space and Contains

To select elements with specific classes accurately, XPath utilizes the following selector:

//*[contains(concat(" ", normalize-space(@class), " "), " foo ")]
  • normalize-space() removes leading and trailing whitespace.
  • concat() appends a space before and after the class attribute value.
  • contains() checks if the concatenated string includes the target class.

Equivalence and Further Implications

The XPath selector provided is equivalent to the CSS selector *[class~="foo"], which matches elements with classes that contain the target class. Understanding these nuances is crucial for XPath proficiency.

The above is the detailed content of How Can I Accurately Select CSS Classes Using XPath?. 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