1

Is it possible to select elements with class values like this:

<div class="a b"></div>
<div class="a c"></div>
<div class="a d"></div>
<div class="a e"></div>
<div class="a f"></div>

I need select all of the div elements who's class attribute value has a...

I tried something like this:

$items = $xpath->query('//div[@class="a *"]');

I tried without *, but it also returned nothing.

What is the correct XPath to select these elements by their class attribute values?

Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
MagicHat
  • 379
  • 1
  • 6
  • 28
  • 1
    is that a typo? `class"a b"` that class attribute is malformed, or just editing error in your question – Kevin Apr 18 '18 at 01:54

2 Answers2

2

Pad the class attribute with leading and trailing spaces and look for "a":

//div[contains(concat(' ',@class,' '), ' a ')]

That way it will match whether the "a" value is anywhere in the class attribute value, and won't match on false positives for things such as class="baz"

Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
  • This variant should help in some other situation, and my too... tks too man. – MagicHat Apr 18 '18 at 02:00
  • This is the right answer, +1 (or see the [**duplicate link**](https://stackoverflow.com/q/1390568/290085) for additional variations and discussion). – kjhughes Apr 18 '18 at 02:27
0

As pointed out by kjhughes, this is a bad answer because it matches everything that has an 'a' inside.

You can try the xpath query //div[contains(@class, "a")] if you want to find any div that has the class attribute that contains "a"

csb
  • 674
  • 5
  • 13
  • You win, perfect...prrrrrrrrrrrrrrr, flawless victory! tks a lot! – MagicHat Apr 18 '18 at 01:58
  • Despite OP's elation, this is a bad answer (-1) as it would match `class="bad"` too. See [**Mads Hansen's answer**](https://stackoverflow.com/a/49889986/290085) or the [**duplicate link**](https://stackoverflow.com/q/1390568/290085) for the right way to test whether `@class` attribute value contains a certain value. – kjhughes Apr 18 '18 at 02:25