Check if any element with a certain class is empty
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?
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>
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>
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>
上一篇: 如何设置整个网站或一个网页或两者的JavaScript / jQuery代码?
下一篇: 检查任何具有某个类的元素是否为空