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,713
  • 6
  • 59
  • 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
  • 275,078
  • 51
  • 420
  • 480
  • @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,012
  • 6
  • 49
  • 55
0

Given that the structure will always look like it does:

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

It is globally unique since it is has an ID.

EDIT: Try

$(this).parent().prev();
Slappy
  • 3,932
  • 1
  • 26
  • 40
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
  • 34,318
  • 11
  • 78
  • 107
0
$('#read-more') will do the trick
James Kyburz
  • 12,741
  • 1
  • 31
  • 33