Reputation: 5
in the code bellow how can i select the span element with id="read-more" if iam in the anchor element with id="preface-more-btn" using $(this) (to be applied for more than one button) in jquery?
<pre>
<div id="content">
<p>
<span style="font-size: 16px;"></span>
</p>
<span id="read-more" style="display: none;"></span>
<div class="more active" id="preface-more">
<a class="btn-more" id="preface-more-btn" href="#"></a>
</div>
</div>
</pre>
thank you for helping..
Upvotes: 0
Views: 245
Reputation: 4092
var selector = $('#read-more');
It is globally unique since it is has an ID.
EDIT: Try
$(this).parent().prev();
Upvotes: 0
Reputation: 298176
If you're contextually within the element with id="reface-more-btn"
, you can select it intuitively like this:
$(this).parent().parent().find('#read-more');
If you're looking for readability, try this:
$(this).closest('#read-more');
But since the id
is unique to only one element, why aren't you just using $('#read-more');
?
You might be confusing class
and id
, as only one element can have a certain id
, while many elements can share a class
. Read this question for a longer explanation, as it's essential to know the differences: div class vs id.
Upvotes: 2
Reputation: 35598
Well, selecting an element by id is quite easy.
$("#read-more")
Will do it regardless of where you are because the id's are global.
Upvotes: 0
Reputation: 17156
Given that the structure will always look like it does:
var theSpan = $(this).parent().parent().find('#read-more');
Upvotes: 0