Marcin S.
Marcin S.

Reputation: 11191

How to find elements by substring of ID using selector-syntax Jsoup?

I have used Jsoup to fetch a page from a URL. I can extract the link of certain id using the following line of code:

Elements links = doc.select("a[href]#title0"); 

How can I find the elements if I only know the part of its ID for example 'title'. I know that I could find all the a links with the href and then iterate through the 'links' and check whether it's id contains 'title' substring or not however I would like to avoid this approach. Is there a way to filter the links in the selector and check whether it's id contains 'title' substring?

Upvotes: 6

Views: 4291

Answers (2)

Malek
Malek

Reputation: 198

@alex-ackerman 's answer is half correct, but the other half is wrong.

[attr^=valPrefix] elements with an attribute named "attr", and value starting with "valPrefix" [attr$=valSuffix] elements with an attribute named "attr", and value ending with "valSuffix" [attr*=valContaining] elements with an attribute named "attr", and value containing "valContaining" [attr~=regex] elements with an attribute named "attr", and value matching the regular expression The above may be combined in any order

http://jsoup.org/apidocs/org/jsoup/select/Selector.html

Upvotes: 2

Alex Ackerman
Alex Ackerman

Reputation: 1341

You can use something like:

Elements links = doc.select("a[id^=nav]");

this would return all the links with id starting with string "nav"

The following will return all the links with id containing string "logo"

Elements links = doc.select("a[id~=logo]");

Upvotes: 9

Related Questions