tags:

views:

321

answers:

3

Hi,

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.

A: 

Your code is parsed as a call to element.parent with the argument 'a'.length.
It is therefore equivalent to element.parent(1), which is an invalid call.

You need to get the length of the jQuery object by moving .length after the ), like this:

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

Also, this will not work if element is nested in some other tag which is itself in an <a> tag.
You might want to call closest instead.

SLaks
+1  A: 

The first line should be:

if (element.parent('a').length > 0)
RoToRa
+1  A: 

Assuming element is actually a jQuery object:

if (!element.parent().is("a")) {
  element.wrap("<a>")
}  
element.parent().attr("href", link);

If element is a DOM node:

if (!$(element).parent().is("a")) {
  $(element).wrap("<a>")
}  
$(element).parent().attr("href", link);
cletus
@cletus dominates the arena. +1
macek