user3439968
user3439968

Reputation: 3538

Mojolicious, Mojo::DOM select tag by contains text

Is there analog ":contains()"(JQuery, JSoup) selector in Mojolicious?

Selector ":contains('text') ~ td + td" work in JQuery and JSoup. How can I convert it to Mojolicious selector?

http://api.jquery.com/contains-selector/

Description: Select all elements that contain the specified text.

version added: 1.1.4jQuery( ":contains(text)" ) text: A string of text to look for. It's case sensitive.

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

:contains(text) elements that contains the specified text. The search is case insensitive. The text may appear in the found element, or any of its descendants.

Mojolicious analog?

Upvotes: 2

Views: 885

Answers (2)

user3439968
user3439968

Reputation: 3538

Few experiment with hobbs code and I can repeat JQuery, JSoup selector result:

:contains('some string') ~ td + td

Mojo:

$dom 
-> find('*')
-> grep(sub { $_ -> text =~ /some string/; })
-> map('following', '~ td + td') 
-> flatten;

But, I don't think it's universal and best way to do such select. Just for start.

text

Extract text content from this element only (not including child elements), smart whitespace trimming is enabled by default.

flatten

Flatten nested collections/arrays recursively and create a new collection with all elements.

Upvotes: -1

hobbs
hobbs

Reputation: 240030

Untested, but I would go in the direction of

$dom->find('*')
    ->grep(sub { $_->all_text =~ /text/ })
    ->map('following', 'td')
    ->map('find', 'td')

(if you have something more specific before your :contains, like at least a tag name selector, then replace the * with that, which should greatly help the performance).

Upvotes: 5

Related Questions