2

I am looking to scan a page and look for any html elements that have a class or id that contains the word price. My thought was to use regex here but I cannot get it to fire correctly.

I am using Safari and Chrome on OS X

var price = $("div:regex(\bprice\b)").text();

The purpose is to get the price of a product on an e-commerce site if it isn't already stated in Open Graph which is already handled.

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
Justin Erswell
  • 688
  • 7
  • 42
  • 87
  • Interesting alternate way of doing this : http://stackoverflow.com/questions/1163888/jquery-get-only-all-html-elements-with-ids Though may be a perf slug :( But still, interesting. – Jason Evans Aug 30 '13 at 08:13

3 Answers3

3

"\b" is same as "\x08".

Escape \:

var price = $("div:regex(\\bprice\\b)").text();
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • thanks for this however i am getting this in the console `Error: Syntax error, unrecognized expression: unsupported pseudo: regex` – Justin Erswell Aug 30 '13 at 08:07
  • 3
    `regex` isn't part of jQuery, you have to use http://james.padolsey.com/javascript/regex-selector-for-jquery/ – Barmar Aug 30 '13 at 08:08
  • Great thanks for this getting this now any thoughts? `TypeError: 'undefined' is not an object (evaluating 'match[3]')` – Justin Erswell Aug 30 '13 at 08:12
2

A simple way is to use contains word selector:

$('div[id~="price"], div[class~="price"]')

See http://api.jquery.com/attribute-contains-word-selector/

sinsedrix
  • 4,336
  • 4
  • 29
  • 53
  • I have tried using this `$('div[id~="price"], div[class~="price"], span[id~="price"], span[class~="price"], p[class~="price"], p[id~="price"]').first().text();` and it works well however seems a little messy any thoughts? – Justin Erswell Aug 30 '13 at 08:18
  • 1
    So just use `$('[id~="price"], [class~="price"]')` – sinsedrix Aug 30 '13 at 08:21
0

You can do that by adding new pseuo selector:

jQuery.expr[':'].regex = function(elem, index, match) {
    var regex = new RegExp(match[3]),
        $elem = $(elem);
    return regex.test($elem.attr('class')) || regex.test($elem.attr('id')); 
};

and you can use this selector using:

$("div:regex(\\bprice\\b)")
jcubic
  • 61,973
  • 54
  • 229
  • 402