David Garcia
David Garcia

Reputation: 2696

jquery wrap, append, prepend to parent div

I am trying to detect when a certain div element has a height of 0 in order to display a div element with a message.

function checkads() 
{
    if ($('#container').height() == 0) 
    {
        $('.wp_bannerize').wrap($('<div id="notice">ENABLE ADS</div>'));
    };
}

$(document).ready(checkads);

The above works fine, however, is there anyway to make the script wrap the parent div that is 1 or 2 levels above the child div without having to define the class name of the parent manually "wp_bannerize"

Upvotes: 1

Views: 1398

Answers (2)

Riley Lark
Riley Lark

Reputation: 20890

You can use $('#container').parent().parent() to find the parent of the parent, for example. You can also use $('#container').closest('div') to search through the parent list for the closest div (or whatever). You don't need to know the class name (although you can also use that with closest!)

Upvotes: 1

DarkAjax
DarkAjax

Reputation: 16223

You could try something like this:

function checkads() {
    var $container = $('#container');
    if ($container.height() == 0) {
        $container.parent().wrap($('<div id="notice">ENABLE ADS</div>'));
        // OR $container.parent().parent().wrap($('<div id="notice">ENABLE ADS</div>'));
    }
}

Or change your checkads() function to:

function checkads($current) {
    if ($current.height() == 0) {
        $current.parent().wrap($('<div id="notice">ENABLE ADS</div>'));
    }
}

And call it like:

checkads($('#container');
checkads($('#container2');
//etc...

Upvotes: 1

Related Questions