jQuery - How to determine if a parent element exists?

Dan picture Dan · Apr 22, 2010 · Viewed 36.4k times · Source

I'm trying to dynamically and a link to an image, however I cannot correctly determine is the parent link already exists.

This is what I have,

if (element.parent('a'.length) > 0)
{   
      element.parent('a').attr('href', link);            
}
else
{   
      element.wrap('<a></a>');
      element.parent('a').attr('href', link);     
}

Where element refers to my img element and link refers to the url to use.

Every time the code runs, the else clause is performed, regardless of whether or not the img tag is wrapped in an a tag.

Can anyone see what I'm doing wrong?

Any advice appreciated.

Thanks.

Answer

RoToRa picture RoToRa · Apr 22, 2010

The first line should be:

if (element.parent('a').length > 0)