This is correct.

I actually wrote a few jQuery extensions that handle this.

The code is:

$.fn.extend({
// checks to see if an element exists
// if no callback is supplied, returns
// a boolean value stating if the element
// exists, otherwise executes the callback
exists: function (callback) {
if (typeof( callback ) === "function") {
if (this.length > 0) { callback.call( this ); }
return this;
}
else { return this.length > 0; }
},
 // checks to see if an element does not
// exist.  if no callback is supplied, returns
// a boolean value stating if the element does
// not exists, otherwise, executes the callback
absent: function (callback) {
if (typeof( callback ) === "function") {
if (this.length === 0) { callback(); }
return this;
}
else { return this.length === 0; }
}
});

Syntax would be

var that = this; // scope
$(this).parents("ul").absent(
function () {
$(that).addClass("active");
}
);

or if you needed to do an if/else type scenario:

var that = this;
$(this).parents("ul").exists(
function () {
// this === $(this)
this.removeClass("active");
}
).absent(
function () {
$(that).addClass("active");
}
);

Or you could also use the function to return a boolean value:

$(this).parent("ul").exists(); // true if ul is present
$(this).parent("ul").absent(); // true if no ul is present


Thanks,
Matt

On Wed, Jan 13, 2010 at 6:52 PM, pedalpete <p...@hearwhere.com> wrote:

> Everything that I've seen says you have to check the length of the
> element you are looking for.
>
> So I think you want
> <pre>
> if($(this).parents('ul').length==0){
>   $(this).addClass("active");
> }
> </pre>
>
> If a parent UL was found, the length would be > 0
>

Reply via email to