最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery Selector with regex - Stack Overflow

programmeradmin3浏览0评论

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-merce site if it isn't already stated in Open Graph which is already handled.

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-merce site if it isn't already stated in Open Graph which is already handled.

Share Improve this question edited Aug 30, 2013 at 8:05 Jason Evans 29.2k15 gold badges94 silver badges156 bronze badges asked Aug 30, 2013 at 8:04 Justin ErswellJustin Erswell 7087 gold badges44 silver badges90 bronze badges 1
  • Interesting alternate way of doing this : stackoverflow./questions/1163888/… Though may be a perf slug :( But still, interesting. – Jason Evans Commented Aug 30, 2013 at 8:13
Add a ment  | 

3 Answers 3

Reset to default 3

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

Escape \:

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

A simple way is to use contains word selector:

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

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

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)")
发布评论

评论列表(0)

  1. 暂无评论