philldam philldam - 1 year ago 132
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:


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


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


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

Answer Source

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){ 
<script src=""></script>
  <h2> Some text here </h2>
  <p>Some text here too</p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download