Search code examples
jqueryparent

jQuery - How to determine if a parent element exists?


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.


Solution

  • The first line should be:

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