Saloso
Saloso

Reputation: 11

How to select all elements whose id contains a particular substring?

I want to select all elements whose id contains a particular substring. For example for these:

<div id="foobootoo"><div>
<div id="foowoohoo"><div>
<div id="foodoowoo"><div>
<div id="soobootoo"><div>

I want to get elements that has foo in the id.

Upvotes: 1

Views: 1466

Answers (4)

JeanValjean
JeanValjean

Reputation: 17713

Looks at the CSS3 selectors (e.g., see this Web page). You can use the following selector:

div[id*="foo"]

and you will select all the divs that contains the substring "foo" in the id.

However, if you want only the divs with an id that starts with "foo", use

div[id^="foo"]

If you rearrange the id of your divs as follows:

<div id="foo-bootoo"><div>
<div id="foo-woohoo"><div>
<div id="foo-doowoo"><div>
<div id="soo-bootoo"><div>

you can use:

div[id|="foo"]

to select all the divs whose id starts with foo and the rest of the id is separated by an hyphen (thus, only the first three).

Moreover, if you rearrange the id of your divs as follows (i.e., by putting the substring "foo" at the end of the id):

<div id="bootoofoo"><div>
<div id="woohoofoo"><div>
<div id="doowoofoo"><div>
<div id="bootoosoo"><div>

you can use:

div[id$="foo"]

to select all the divs whose id ends with foo (i.e. only the first three).

It is worth to mention that there are other selectors, but these seems to be the ones that match your needs.

Upvotes: 0

Alain Pannetier
Alain Pannetier

Reputation: 9514

Did you try something like...

$result = $xml->xpath("div[contains(@id,'foo')]");

Upvotes: 1

blake305
blake305

Reputation: 2236

If you want to select multiple elements, just give the elements the same class.

<div id="foobootoo" class="foo"><div>
<div id="foowoohoo" class="foo"><div>
<div id="foodoowoo" class="foo"><div>
<div id="soobootoo" class="foo"><div>

Upvotes: 1

Mihai Toader
Mihai Toader

Reputation: 12243

First of all your markup seems broken. Once you fix it like this:

<div id="foobootoo"></div>
<div id="foowoohoo"></div>
<div id="foodoowoo"></div>
<div id="soobootoo"></div>

if you use this xpath you will get only the first three nodes: //div[contains(@id, 'foo')].

Upvotes: 2

Related Questions