4

I have this document structure

<div id="log">
<div>ABC</div>
<br/>
<div>DEF</div>
<br/>
...
</div>

Where ... represents any number of div, br pairs.

Now I need to write a JQuery function called exists that takes an id (in this case "log") and a string (for example "DEF") and checks if in the "log" div there is any div whose text matches "DEF". My JQuery is weak, can someone help me with this?

2
  • See this post, i believe this is a duplicate: stackoverflow.com/questions/2722582/…
    – adam
    Aug 31, 2012 at 16:51
  • Thanks all. That was awesome. Here's another question. How do I get a list/array of the content of all the divs in "log"? Aug 31, 2012 at 16:55

5 Answers 5

4
if ( $('#log div:contains("DEF")').length ) {
   // exists
}
2
  • Wow, that was fast, you are good. Just tried this. It works. I don't understand why though. Could you explain it? I totally don't understand the use of .length. Aug 31, 2012 at 16:52
  • @SachinKainth length returns the number of elements in the jQuery object, here if there is a div that contains the word DEF length value is more than 0 which is a truthy value in JavaScript, hence that element(s) exists.
    – Ram
    Aug 31, 2012 at 16:55
3
$("#log").children("div").each(function(){
   if( $(this).text() == "DEF")
     //do something  
});
1
$('#log').find('div:contains("DEF")');

Should work.

1
$searchThis = $('.log').html();
if($searchThis.indexOf('search string') != -1){
    actions upon success (you found the string)
}
1

You can make a selector string from the id, using the :contains selector:

function exists(id, content) {
  return $('#' + id + ' div:contains("' + content + '")').length > 0;
}

That however doesn't make an exact match. You would get a false positive if you want a div that contains exactly EAR, and there is a div containing BEARS. To make an exact match you can filter the elements using the filter method:

function exists(id, content) {
  return $('#' + id).filter(function(){
    return $(this).text() == content;
  }).length > 0;
}

Edit:

To get the contents of all the divs, use the map method:

var arr = $('#' + id + ' div').map(function(){
  return $(this).text();
}).get();

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.