0

I'm trying to addClass on prev() if $(this) is empty or removeClass if itsn't, but can't make it work:

function sfVide(){
    var noentry = false;
    $('.sf').each(function(){
        if($(this).val().trim()==""){
            noentry = true;
            $(this).prev().addClass("test");
        }
      else {
    $(this).prev().removeClass("test");
        }
    });
    return noentry;
}

HTML

<a class="sf--trigger">Subs</a>
<div class="sf"></div>

Live codepen for testing: https://codepen.io/mSyx/pen/MWayKQx

mSyx
  • 19
  • 7

1 Answers1

1

.val() is for use with input elements. In your example, you should probably use text() (you could also use html()):

$('.sf').each(function(){
    if( $(this).text().trim() == "" )
    {
        noentry = true;
        $(this).prev().addClass("test");
    }
    else 
    {
      $(this).prev().removeClass("test");
    }
});
.btn {
  background: blue;
  display: block;
  height: 100px;
  width: 100px;
}

.btn.test {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="btn"></a>
<div class="sf"></div>
BenM
  • 52,573
  • 26
  • 113
  • 168