views:

40

answers:

3

I am trying to select an element in the list depending on its html content. I was hoping to 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.

A: 

you could try the :contains() selector

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

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

For an exact match (from the link above):

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

Usage:

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

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

Daniel Dyson
Ha, snap.... :)
Mark B
A: 

Take a look at the contains() selector:

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

Mark B
That doesn't quite cut it, because that doesn't guarantee uniqueness, i.e. for `<ul><li>some</li><li>something</li></ul>` using `$('li:contains("some")')` both will be selected.
Shagglez
See my updated answer for an exact match extension
Daniel Dyson
A: 

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]);
    }
});
Shagglez
This doesn't work in IE 6 because $(elem).html() returns "john ". You need to call trim() function as in my answer to make this work in all cases. Unfortunately a lot of people still use IE 6
Daniel Dyson
Seems to work well in IE Tester....
Shagglez
Don't count on that. It is not the same as running it in IE6 standalone. Unfortunately, I work in a Bank. Nothing wrong with that per se, but the majority of workstations in most banks are still IE 6. They have a very slooow upgrade cycle. It doesn't work on any of our machines here without the trim. It doesn't do any harm to put it in. Good luck.
Daniel Dyson
True. We don't actually support or develop for IE6, so it's not an issue. But I'll accept your answer for completeness.
Shagglez
Appreciate that. Wish I didn't have to either. :)
Daniel Dyson