0

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..

Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79
andrew
  • 5
  • 4

6 Answers6

2

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.

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
  • @Jeff: He states "to be applied for more than one button", even thought *that* is wrong. – Mikael Östberg Apr 06 '11 at 05:17
  • The OP might be confusing `id` and `class`. – Blender Apr 06 '11 at 05:17
  • if the OP already has a JQuery command that he is calling on the button maybe he just wants to chain that with what he wants to do with #read-more, so he saves a line and avoids searching the DOM – Porco Apr 06 '11 at 05:19
0

This will always work:

$("#read-more");
Corey Sunwold
  • 10,194
  • 6
  • 51
  • 55
0

Given that the structure will always look like it does:

var theSpan = $(this).parent().parent().find('#read-more');
Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79
0
var selector = $('#read-more');

It is globally unique since it is has an ID.

EDIT: Try

$(this).parent().prev();
Slappy
  • 4,042
  • 2
  • 29
  • 41
0

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.

Chris Thompson
  • 35,167
  • 12
  • 80
  • 109
0
$('#read-more') will do the trick
James Kyburz
  • 13,775
  • 1
  • 32
  • 33