Cheerio: How to select element by text content?

前端 未结 2 727
-上瘾入骨i
-上瘾入骨i 2021-02-05 07:29

I have some HTML like this:

Code: 12345
Category: faucets         


        
2条回答
  •  误落风尘
    2021-02-05 08:07

    The reason your code isn't working is because [innerHTML] is an attribute selector, and innerHTML isn't an attribute on the element (which means that nothing is selected).

    You could filter the span elements based on their text. In the example below, .trim() is used to trim off any whitespace. If the text equals 'Category:', then the element is included in the filtered set of returned elements.

    var category = $('span').filter(function() {
      return $(this).text().trim() === 'Category:';
    }).next().text();
    

    The above snippet will filter elements if their text is exactly 'Category:'. If you want to select elements if their text contains that string, you could use the :contains selector (as pointed out in the comments):

    var category = $('span:contains("Category:")').next().text();
    

    Alternatively, using the .indexOf() method would work as well:

    var category = $('span').filter(function() {
      return $(this).text().indexOf('Category:') > -1;
    }).next().text();
    

提交回复
热议问题