HitTheSky HitTheSky - 1 month ago 10
HTML Question

Looping through an array of elements and hiding element if condition true

I have a carousel and within each of the images a nested URL, some of the URLs will contain text others won't. The problem I am facing is that the styling for the URL is appearing even if there is no text for that URL. I would like to hide the URL if there is no text. Below is my HTML structure



var CaptionItems = $('#slideshow').find('.Caption');

$(CaptionItems).each(function() {
if (CaptionItems.text() === "") {
$('#slideshow').find('.Caption').hide();
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="owl-wrapper-outer">
<div class="owl-wrapper owl-origin">
<div class="item">
<a href="#" class="Caption">Nothing to see, move along!</a>
<img src="#" alt="barbady.jpg">
</div>
</div>
<div class="owl-item" style="width: 679px;">
<div class="item">
<a href="#" class="Caption"></a>
<img src="#" alt="rubics.png">
</div>
</div>
<div class="owl-item" style="width: 679px;">
<div class="item">
<a href="#" class="Caption">Some Text</a>
<img src="#">
</div>
</div>
</div>
</div>





I've checked this in the console, it seems to be hiding what is contained in
CaptionItems
but not what's on the actual page. Any pointers would be appreciated.

Answer

Your issue is because you need to reference the current element's text within the iteration, not all the elements together. Try this;

var CaptionItems = $('#slideshow').find('.Caption');
$(CaptionItems).each(function () {
   if ($(this).text().trim() === "") {
       $(this).hide();
   }
});

Note the use of the this keyword above, and calling hide() on the .Caption element directly.

Also note that you can make this code simpler with the use of filter():

$('#slideshow .Caption').filter(function() {
    return $(this).text().trim() == '';
}).hide();