philldam philldam - 1 month ago 15
jQuery Question

Check if more than one element :contains certain text

I'm trying to get a function to fire only if more than one element in a div contains a certain text. I've tried the following approach, but cant seem to make it work:

HTML

<div>
<h2> Some text here </h2>
<p> Some text here too </p>
</div>


jQuery

$(document).ready.(function(){
$('h2 && p:contains("text")'). //Do something ();

});


In this case the code should "Do something", because both h2 and p contain "text".

Answer

You can check if the number of elements is more than 1 with length like this:

$(document).ready(function() {
  if ($('div *:contains("text")').length > 1){ 
    $('div').css('background','red')
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h2> Some text here </h2>
  <p>Some text here too</p>
</div>

Comments