Reputation: 21924
If I have the following:
<div id="wrapper">
<h3>Title</h3><!-- I want to select this -->
<a name="anchor-name"></a>
<div class="section">
<h4>Sub section</h4>
<a name="subsection-name"></a> <!-- this is selected -->
<div class="subsection"></div>
</div>
<h3>Title</h3>
<a name="anchor-name"> </a>
<div class="section">
<h4>Sub section</h4>
<a name="subsection-name"></a>
<div class="subsection"></div>
</div>
<h3>Title</h3>
<a name="anchor-name"></a>
<div class="section">
<h4>Sub section</h4>
<a name="subsection-name"></a>
<div class="subsection"></div>
</div>
</div>
And I have the anchor selected (as indicated) how do I access the <h3>Title</h3>
? I want to get the nearest "parent h3"...
Upvotes: 1
Views: 1348
Reputation: 253318
Before we go any further it's worth noting that the h3
is not a parent of the a
element. However, the following should select the h4
, assuming consistent HTML structure:
$(this).closest('div.section').prevAll('h3:first');
Incidentally, if the this snippet of HTML is contained within another element, to give:
<div class="contentWrapper">
<h3>Title</h3>
<a name="anchor-name"></a>
<div class="section">
<h4>Sub section</h4>
<a name="subsection-name"></a> // this is selected
<!-- ...other stuff... -->
</div>
Then it'd be easiest to use:
$(this).closest('.contentWrapper').find('h3');
References:
Upvotes: 4
Reputation: 1322
The h3 isn't a parent, its a child within a parent object, whats "containing" the h3?
Imagine it is another div, with an id of main-holder.. and that the selected a is $(this):
$h3 = $(this).parent("#mainholder").children("h3")
Upvotes: 1
Reputation: 82219
Use the jQuery closest()
function;
$("a[name=subsection-name]").closest("h3");
Upvotes: -1