1
$(document).ready(function()
{
    $('button').on('click', function()
    {            
        $('.container').children().eq(1).append($('p.important').text());
    });
});

<div class="container">
    <p>1</p>
    <p>2</p>

    <button>Lawl, a button.</button>

    <p>3</p>
    <p class="important">Text to be copied</p>
</div>

I want to find the closest upper p tag to my button. For example, if I move button under <p>1</p>, it should append values to it. If I move my button to bottom, it should add append values to <p>3</p>.

Is it possible with my current HTML?

Ram
  • 143,282
  • 16
  • 168
  • 197
Aristona
  • 8,611
  • 9
  • 54
  • 80
  • I've tried closest() function. For some reason, it never returned me the closest p value. Even with closest('p') function lying aroung, it kept appending value to all p's. – Aristona Sep 11 '12 at 12:32

3 Answers3

2

You can use next or prev method.

.next( [selector] ): Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

.prev( [selector] ): Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.

$('.container button').on('click', function(e) {
      e.preventDefault(); 
      var txt = $('p.important').text();
      $(this).next('p').append(txt);    
});
Ram
  • 143,282
  • 16
  • 168
  • 197
  • I've confused myself with closest() function. It sounds like it would obtain the closest target, but it finds the closest parent. I'll probably use next(), and doublecheck prev() incase button is at bottom. Thank you, it solved my question. – Aristona Sep 11 '12 at 12:47
1

Try closest method. It must do the trick!

$("button").click(function(){
    $(this).closest('p');
})
Mathieu Mahé
  • 2,647
  • 3
  • 35
  • 50
0

You can either use one of the following, depending on your needs:

KyorCode
  • 1,477
  • 1
  • 22
  • 32