-1

So far I have this:

<span class="description">Description 1</span>
<button class="select">Select!</button>

<span class="description">Description 2</span>
<button class="select">Select!</button>

<span class="description">Description 3</span>
<button class="select">Select!</button>

<span class="description">Description 4</span>
<button class="select">Select!</button>

I want button to select text inside "description" class element, but only for previous one. Is that possible? Aka if user clicks on first select button, Description 1 will be selected.

Note: In selection I mean that the text should be highlighted. Thanks in advance

T J
  • 42,762
  • 13
  • 83
  • 138
George
  • 95
  • 2
  • 2
  • 7

2 Answers2

2

Use prev() to get the previous element:

 $("button").click(function(){
      var text = $(this).prev().text();
      alert(text);
 }); 

See Demo: http://jsfiddle.net/maxdK/

Curtis
  • 101,612
  • 66
  • 270
  • 352
  • Great, thanks but I want it to highlight the text, not alert it. So that user can right click and copy selected text – George Aug 13 '12 at 11:39
  • @GeorgeLubaretsi, http://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse – Adi Aug 13 '12 at 11:41
  • 1
    @GeorgeLubaretsi This answers your question, your question doesn't mention that text should be highlighted. you can simply delete the alert part. – Ram Aug 13 '12 at 11:43
1

To highlight the text you can change the style of text or can apply any css attribute like
$(this).prev().css("background-color","red");

or you can add any css

$(this).prev().addClass("css-class");
Buzz
  • 6,030
  • 4
  • 33
  • 47