如何选择匹配.text() == ""条件

How do I select an element that matches a .text() == "" condition?

本文关键字:quot 条件 text 何选择 选择      更新时间:2023-09-26

这就是我想做的:

<label class="myClass"></label> <!-- I want to hide this -->
<label class="myClass">Some text here</label> <!-- Don't hide -->
$('label.myClass').text() == "" ) {
        $('this').hide();
 }

当然,$(this)指向window,而不是满足条件的label.myClass。我如何重写,让我选择所有没有文本的标签呢?

var label = $('label.myClass').filter(function (index) {
    if ($(this).text() == "") {
        return $(this)
    }
})
console.log(label.attr('class'))
console.log(label.text())
console.log(label.length)

使用.filter()

演示

你可以这样做:

$( "label.myClass" ).each(function( index ) {
 if ($(this).text() == "") {
   $(this).hide();
     }
 });

尝试使用:empty选择器

$("label.myClass:empty").hide()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<label class="myClass"></label> <!-- I want to hide this -->
<label class="myClass">Some text here</label> <!-- Don't hide -->