JQuery “contains” returns nothing for html encodin

2020-04-11 10:44发布

var foundin = $('*:contains("the")').last();

works on a page, but

var foundin = $('*:contains("&copy")').last();

returns nothing, even though '&copy' does appear in the page source. I tried escaping the '&', but that doesn't work either. Is there a way to use contains to find an html encoded character in a page?

Basically, what I want to do is find the element contains © and parse it to get the copyright holder. I asked a similar question aiming at this with regex here: select HTML text element with regex?

1条回答
何必那么认真
2楼-- · 2020-04-11 11:46

The quick and dirty:

var $div = $("<div>");

$.expr[":"].containsEnc = function(a, b, c, d) {
    var decoded = $div.html(c[3]).text(); // decode &copy to ©

    return ~a.textContent.indexOf(decoded); // does the element contain the character
};

Then you can use containsEnc as a selector:

$('body:containsEnc("&copy")').html('ok');

It may not be the safest and most performant, though.

http://jsfiddle.net/wfLur/1/

查看更多
登录 后发表回答