Add support for [attr~="value"] selector (attribute contains word)
Jakub Narebski [Sun, 9 Jan 2011 12:31:36 +0000 (13:31 +0100)]
http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
http://api.jquery.com/attribute-contains-word-selector/

  This selector matches the test string against each word in the
  attribute value, where a "word" is defined as a string delimited by
  whitespace.  The selector matches if the test string is exactly equal
  to any of the words.

lib/HTML/Zoom/SelectorParser.pm
t/selectors.t

index 9bc7bc3..be08175 100644 (file)
@@ -81,6 +81,17 @@ sub _raw_parse_simple_selector {
         }
       };
 
+    # '[attr~=bar]' - match attribute contains word
+    /\G\[$sel_re~=$match_value_re\]/gc and
+      return do {
+        my $attribute = $1;
+        my $value = $2;
+        sub {
+          $_[0]->{attrs}{$attribute}
+          && grep { $_ eq $value } split(' ', $_[0]->{attrs}{$attribute});
+        }
+      };
+
     # '[attr=bar]' - match attributes
     /\G\[$sel_re=$match_value_re\]/gc and
       return do {
@@ -92,7 +103,7 @@ sub _raw_parse_simple_selector {
         }
       };
 
-    # '[attr] - match attribute being present:
+    # '[attr]' - match attribute being present:
     /\G\[$sel_re\]/gc and
       return do {
         my $attribute = $1;
index 09875ad..13a8154 100644 (file)
@@ -89,6 +89,14 @@ is( HTML::Zoom->from_html('<div f="foo bar"></div>'.$stub)
    '<div f="foo bar">grg</div>'.$stub,
    'E[attr*="val"] works' );
 
+# el[attr~="foo"]
+is( HTML::Zoom->from_html('<div frew="foo bar baz"></div>'.$stub)
+   ->select('div[frew~="bar"]')
+      ->replace_content('grg')
+   ->to_html,
+   '<div frew="foo bar baz">grg</div>'.$stub,
+   'E[attr~="val"] works' );
+
 # [attr=bar]
 ok( check_select( '[prop=moo]'), '[attr=bar]' );