Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to determine if a parent element exists?

Tags:

jquery

parent

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.

like image 255
Dan Avatar asked Apr 22 '10 14:04

Dan


People also ask

How do you check if an element exists or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

How do I find a specific parent in jQuery?

The parents() is an inbuilt method in jQuery which is used to find all the parent elements related to the selected element. This parents() method in jQuery traverse all the levels up the selected element and return that all elements.

Which jQuery method returns the direct parent element of the selected element?

jQuery parent() Method The parent() method returns the direct parent element of the selected element.


2 Answers

The first line should be:

if (element.parent('a').length > 0)
like image 135
RoToRa Avatar answered Sep 20 '22 20:09

RoToRa


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);
like image 20
cletus Avatar answered Sep 18 '22 20:09

cletus