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

How to Select a CSS Class Using XPath?

Linda Hamilton
Release: 2024-12-08 18:30:15
Original
510 people have browsed it

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"]'); 
Copy after login

Solution:

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

Correct XPath Syntax:

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

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>
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template