Doug Fir
Doug Fir

Reputation: 21212

Select grand parent element attribute

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>

Upvotes: 0

Views: 824

Answers (3)

Anil kumar
Anil kumar

Reputation: 4177

you can try like this.

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

or you can also do like this.

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

Upvotes: 3

Tim Bartsch
Tim Bartsch

Reputation: 918

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

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

Upvotes: 2

David Thomas
David Thomas

Reputation: 253318

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:

Upvotes: 4

Related Questions