0

I would like to show a span element, if a div element with a specific class is within the body and hide the span, if the div with the specific class isn't anymore within the body. So I tried to solve this with the jQuery function has(). It works for the first time as expected. But when I rename the specific class of the div to specific-element-1 and reload it, the span is still visible. What am I doing wrong? Here the codepan, so you can easy change the class name to check it: https://codepen.io/STWebtastic/pen/VyObKM

PS: I also tried to solve this with the jQuery functions after() and children() in case of has(), but didn't work. Hope this is clear enough.

$(document).ready(function() {
  if ($('body').has('.specific-element')) {
    $('.showme').show();
  } else {
    $('.showme').hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="specific-element"></div>
  <span class="showme">Hello World!</span>
</body>
webta.st.ic
  • 4,781
  • 6
  • 48
  • 98

1 Answers1

2

Try this

$(document).ready(function() {
  if ($('body .specific-element').length) {
    $('.showme').show();
  } else {
    $('.showme').hide();
  }
});

Updated pen here

kiranvj
  • 32,342
  • 7
  • 71
  • 76