jQuery - How to determine if a parent element exists?

强颜欢笑 提交于 2019-12-04 17:10:58

问题


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.


回答1:


The first line should be:

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



回答2:


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);



回答3:


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.



来源:https://stackoverflow.com/questions/2691873/jquery-how-to-determine-if-a-parent-element-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!