Tuesday, April 17, 2012

jQuery :contains selector to search for multiple strings


Assuming i have:




<li id="1">Mary</li>
<li id="2">John, Mary, Dave</li>
<li id="3">John, Dave, Mary</li>
<li id="4">John</li>



If i need to find all <li> Elements which contain "John" and "Mary", how would i construct the jQuery?



A search for a single string seems easy:




$('li:contains("John")').text()



I am looking for something like the following pseudo code:




$('li:contains("John")' && 'li:contains("Mary")').text()



Thanks!


Source: Tips4all

5 comments:

  1. answer

    I think it's more something like:

    $('li:contains("Mary"):contains("John")').


    explanation

    Just think of :contains just as it wass .someClass:

    $('li.classone, li.classtwo'). //you want either classone OR classtwo
    $('li.classone.classtwo'). //you want BOTH on one element
    /* same with :contains */
    $('li:contains("mary"), li:contains("john")'). // either one OR two
    $('li:contains("mary"):li:contains("john")'). //li, which contains both


    snippet

    proof:

    http://jsbin.com/ejuzi/edit

    ReplyDelete
  2. How about

    $('li:contains("John"),li:contains("Mary")')

    ReplyDelete
  3. Answer

    The correct syntax would be $("li:contains('John'),li:contains('Mary')").css("color","red")

    But I found out that if you had many cases to test, jQuery will perform very badly (especially on IE6, I know, it's old but still in use). So I decided to write my own attribute filter.

    This is how to use it: $("li:mcontains('John','Mary')").css("color","red")

    Code

    jQuery.expr[':'].mcontains = function(obj, index, meta, stack){
    result = false;
    theList = meta[3].split("','");

    var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')

    for (x=0;x<theList.length;x++) {
    if (contents.indexOf(theList[x]) >= 0) {
    return true;
    }
    }

    return false;
    };

    ReplyDelete
  4. It's easy:

    $("li:contains('John'):contains('Mary')")

    ReplyDelete
  5. I think you could learn something from this instead. By using one element such as the paragraph as the example, click the link JS Bin Example it shows you what I mean. The script will dynamically change the content of your page. In my example the script is gonna fire up the alert box, and once you press it away the content of the page will be dynamically changed, it's kind of a useful way to write jQuery in my opinion none the less.

    ReplyDelete