开发者

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&开发者_如何学Cgt;

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


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')].


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>


Did you try something like...

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜