-1

My page contains multiple elements like this:

<span class="field-validation-valid text-danger" data-valmsg-for="CcInfo.CcCheck" data-valmsg-replace="true"></span>
<span class="field-validation-valid text-danger" data-valmsg-for="CcInfo.CcCheck" data-valmsg-replace="true">Something went wrong</span>
<span class="field-validation-valid text-danger" data-valmsg-for="CcInfo.CcCheck" data-valmsg-replace="true"></span>

Now, I'd like to check with JQuery if ANY of these elements contains text. So in this case, it's true, because the second element contains "Something went wrong".

I've tried:

if (!$(".field-validation-valid text-danger").is(':empty')) {
    // do work
}

But apparently it's not that easy.

How to achieve this?

Bv202
  • 3,924
  • 13
  • 46
  • 80
  • 5
    `".field-validation-valid text-danger"` wrong selector, you want: `".field-validation-valid.text-danger"` – A. Wolff Nov 19 '14 at 10:30

3 Answers3

3

You need to check whether there is some content then check, also your selector has a problem it should be .field-validation-valid.text-danger

if (!$(".field-validation-valid.text-danger").html().trim().length) {
    // do work
}

The empty-selector will fail if the checking element has a [space] as its content like <span> </span>

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
3

You can use jQuery.filter() function to filter elements based on custom criteria. The criteria in the below example is that the elements has some non-whitespace text.

$(function() {
  var $notEmptySpans = $(".field-validation-valid.text-danger").filter(function() {
    return $(this).text().match(/\S/) !== null;
  });
  console.log($notEmptySpans);
  if ($notEmptySpans.length > 0) {
    console.log($notEmptySpans.length + " non-empty spans found");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<span class="field-validation-valid text-danger" data-valmsg-for="CcInfo.CcCheck" data-valmsg-replace="true">Something went wrong</span>
<!-- the following are considered empty -->
<span class="field-validation-valid text-danger" data-valmsg-for="CcInfo.CcCheck" data-valmsg-replace="true"></span>
<span class="field-validation-valid text-danger" data-valmsg-for="CcInfo.CcCheck" data-valmsg-replace="true"> </span>
Salman A
  • 262,204
  • 82
  • 430
  • 521
0

You could just

if ($(".field-validation-valid.text-danger").not(':empty').length) {
    // do work
}

Explanation of length: Check if element exists in jQuery

Also note you need to list classes separately. Your sample had a space between class names, which caused it to try selecting a tag name <text-danger>

Community
  • 1
  • 1
blgt
  • 8,135
  • 1
  • 25
  • 28