1

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.

3 Answers 3

1

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>!

Sign up to request clarification or add additional context in comments.

Comments

0

Take a look at the contains() selector:

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

1 Comment

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.
0

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]);
    }
});

4 Comments

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
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.
True. We don't actually support or develop for IE6, so it's not an issue. But I'll accept your answer for completeness.
Appreciate that. Wish I didn't have to either. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.