Select grand parent element attribute

最后都变了- 提交于 2019-12-23 05:03:20

问题


I'm not so sharp on jquery but am setting up an analytics implementation (Using Google Tag MAnager) that uses titles.

I have this line:

var linkTitle = $(this).attr('title');

The this in question is a form checkbox and it has no title attribute. The grand parent li, however, does. I'd like to select the grand parent title attribute. Is that possible?

The structure is like so:

<ul>
 <li>
  <input>

回答1:


you can try like this.

$(this).parent().attr('title');

or you can also do like this.

 $(this).parents('li').attr('title');



回答2:


Use the following:

$(this).closest('li').attr('title');

closest() returns the first element from the ancestors of the $(this) jQuery node/object which matches the selector (li) passed to the method, and will then access its title attribute.

The benefit of using closest() (in place of parent()) is that closest() requires less prior knowledge of the DOM structure, and allows for other ancestors to be inserted between the two (so if the input is wrapped in a new div, or fieldset, it doesn't matter; closest() will still work).

References:

  • attr().
  • closest().



回答3:


You can access the parent element via the parent() function.

var linkTitle = $(this).parent().attr('title');


来源:https://stackoverflow.com/questions/18743846/select-grand-parent-element-attribute

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