开发者

Using html() as an attribute with jQuery

开发者 https://www.devze.com 2023-01-18 15:19 出处:网络
I am trying to select an element in the list depending on its html content. I was hoping t开发者_如何学Pythono do something like $(\'li[html=\"something\"]\'), but of course html isn\'t an attribute.

I am trying to select an element in the list depending on its html content. I was hoping t开发者_如何学Pythono do something like $('li[html="something"]'), but of course html isn't an attribute. Is there an equivalent set based operation?

I could of course iterate all the elements in the list using $.each(), but it seems to me it will be quite a lot slower.


you could try the :contains() selector

http://api.jquery.com/contains-selector/

$("li:contains('something')")

For an exact match (from the link above):

$.expr[":"].contains = function(obj, index, meta, stack){
    return $.trim($(obj).html()) == meta[3];
}

Usage:

$("li:contains('john')")

This will only match <li>John</li>, not <li>A. John</li>, neither <li>John 6</li>... just <li>John</li>!


Take a look at the contains() selector:

http://api.jquery.com/contains-selector/


Thanks for pointing me in the right direction, but the correct solution requires building on that using $.extend. Here is what I came up with:

$.extend($.expr[':'], {
    'hasHtml': function(elem, i, attr) {
        return ($(elem).html() == attr[3]);
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消