Home >Backend Development >PHP Tutorial >How to Select a CSS Class Using XPath?

How to Select a CSS Class Using XPath?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 18:30:15428browse

How to Select a CSS Class Using XPath?

How to Select a CSS Class with XPath

Issue:

You want to select a specific class called ".date" in an HTML document using XPath, but your attempts have been unsuccessful.

Code:

@$doc = new DOMDocument();
@$doc->loadHTML($html);
$xml = simplexml_import_dom($doc); //Simplify XPath
$images = $xml->xpath('//[@class="date"]'); 

Solution:

Unlike CSS, XPath does not natively support class selectors. However, there is a workaround:

Correct XPath Syntax:

//*[contains(concat(" ", normalize-space(@class), " "), " foo ")]

This expression matches any element whose class attribute contains the substring "foo".

Explanation:

  • normalize-space: Removes leading and trailing whitespace.
  • concat: Combines " ", the normalized @class value, and " " to ensure that the class name is surrounded by spaces.
  • contains: Checks if the concatenated string includes " foo ".

Example:

<div>

The XPath query will correctly select the element with the "date" class and ignore the "foobar" element.

Incorrect Approaches:

  • //*[@class="foo"]: Doesn't match elements with multiple classes.
  • //*[contains(@class, "foo")]: Matches elements with a class containing "foo" as a substring, even if it's part of a longer class name like "foobar".

The above is the detailed content of How to Select a CSS Class 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