Reputation: 439
I'm trying to get one div to show if another is empty. This needs to happen multiple times throughout a page. The script won't work in its present state.
Script:
$('.standard_page_list_result').each(function(){
if ($('.children p').length == 0)
$('.summary').css("display", "block");
});
HTML:
<div class="standard_page_list_result"><div class="children"><p>Hello</p></div>
<div class="summary"><p>Goodbye</p></div></div>
<div class="standard_page_list_result"><div class="children"><p>Hello</p></div>
<div class="summary"><p>Goodbye</p></div></div>
<div class="standard_page_list_result"><div class="children"><p>Hello</p></div>
<div class="summary"><p>Goodbye</p></div></div>
<div class="standard_page_list_result"><div class="children"><p></p></div>
<div class="summary"><p>Hello!</p></div></div>
CSS:
.summary { display: none; }
Upvotes: 1
Views: 635
Reputation: 741
Instead of checking the length of the <div>
try using the is() function.
$('.standard_page_list_result').each(function(){
if($(this).find('.children p').is(':empty')) {
$(this).find('.summary').css("display", "block");
}
});
EDIT:
Fixed the code above to select each element rather than affecting all elements if only 1 was empty. Other answer already chosen but for future viewers this is the alternative with using the is() function. Here is a fiddle for it.
Note: empty checks for no white-space too. If there's a single space, then it's not empty
Upvotes: 1
Reputation: 42642
In one line:
$('.standard_page_list_result .children p:empty').parent().next('.summary').css('display','block');
Demo: http://jsfiddle.net/JXDNk/
Upvotes: 3
Reputation: 39037
Just toggle the summary based on the emptiness of the elements:
$('.standard_page_list_result').each(function(){
$('.summary', this).toggle( $('.children p', this).is(":empty") );
});
Upvotes: 1
Reputation: 910
Using your same concept, you need to identify the one your in with this
and then do a find selector in order to make it work. what you were doing was getting the length of all.
$('.standard_page_list_result').each(function(){
if ($(this).find('.children p').text().length == 0)
$(this).find('.summary').css("display", "block");
});
Here is the jsFiddle for you
http://jsfiddle.net/JoshuaPack/4C35E/
Upvotes: 2
Reputation: 78650
$('...').length
will tell you how many elements matched your selector, not if those elements are empty.
To check if the element is empty, I would probably do it like this:
if($.trim($(...).text()).length == 0)
Finally, you'll need to use this
inside your each to target the appropriate elements. Something like this:
$('.standard_page_list_result').each(function(){
var $this = $(this);
if ($.trim($this.find('.children p').text()).length == 0){
$this.find('.summary').css("display", "block");
}
});
Upvotes: 0