Phantom
Phantom

Reputation: 108

Loop through parent elements and if child element doesnt exist display text

I'm trying to figure out how to loop through all parent classes (.grid) and if it doesnt have a child div with class (.image-container) then display (.content-container) within the same (.grid) section.

HTML:

<style>
.grid .content-container {
    display:none;
}
</style>

<div class="grid">
    <div class="art">
        <div class="image-container">
            <img src="image url" />
        </div>
        </div>
        <div class="title">Title Text</div>
        <div class="content-container">Some Content Goes here</div>
</div>
<div class="grid">
    <div class="art"></div>
        <div class="title">Title Text</div>
        <div class="content-container">Some Content Goes here</div>
</div>
<div class="grid">
    <div class="art">
        <div class="image-container">
            <img src="image url" />
        </div>
        </div>
        <div class="title">Title Text</div>
        <div class="content-container">Some Content Goes here</div>
</div>
<div class="grid">
    <div class="art">
        <div class="image-container">
            <img src="image url" />
        </div>
        </div>
        <div class="title">Title Text</div>
        <div class="content-container">Some Content Goes here</div>
</div>
<div class="grid">
    <div class="art"></div>
        <div class="title">Title Text</div>
        <div class="content-container">Some Content Goes here</div>
</div>

Upvotes: 0

Views: 398

Answers (2)

Jared Farrish
Jared Farrish

Reputation: 49208

An alternative, one call:

$('.grid')
    .filter(function fi(){return !$('.image-container', this).length})
    .children('.content-container')
    .show();

http://jsfiddle.net/E8CfL/

Or:

$('.grid')
    .filter(':not(:has(.image-container))')
    .children('.content-container')
    .show();

http://jsfiddle.net/E8CfL/1

Or:

$('.grid:not(:has(.image-container)) .content-container').show();

http://jsfiddle.net/E8CfL/3

Not sure which would be the most efficient, but I have a hunch the first would be.

Upvotes: 1

scrowler
scrowler

Reputation: 24406

Something like this should work:

$('.grid').each(function() {
    if($(this).find('.image-container').length == 0) {
        // no children
        $(this).find('.content-container').show();
    }
});

Upvotes: 1

Related Questions