How to pick up element above Jquery?

Asked

Viewed 6,187 times

4

I have the following elements:

<p class="id-task">5</p>
<p class="status-change">
    <i id="test-task" class="fa fa-flask fa-lg" aria-hidden="true"></i> 
</p>

I’m trying to get number 5 in <p class="id-task">5</p> with the following Jquery code:

$('#test-task').on('click', function(){ 
    var father = $(this).parent().siblings();
    var idTask = $(father).text();
    alert(idTask);  
});

I changed the code, because the parent() end has to be .siblings(), because the <p class="id-task">5</p> is the brother of <p class="status-change"></p>

4 answers

4

the Prev() method returns the previous widget.

$('#test-task').on('click', function(){ 
    var element = $(this).parent().prev();
    var idTask = $(element).text();
    alert(idTask);  
});
  • 1

    I would use something like var id = $(this). Parent(). Parent(). find('id-task'). text();

  • there can be several elements with the class "id-task".

3

Change to $(father).text();, you’re getting all the html.

$('#test-task').on('click', function(){ 
    var father = $(this).parent().parent();
    var idTask = $(father).text();
    alert(idTask);  
});

2

Just take it for the class.

$('.id-task').text();

JS

$('#test-task').on('click', function(){ 
    var idTask = $('.id-task').text();
    alert(idTask);  
});

0

Use the function .prev()

.prev() always brings the previous element

In case your click event calls an element inside a paragraph if you want one above where it is. Do so:

$('#test-task').on('click', function(){ 
    var idTask = $(this).parent().prev().text();
    alert(idTask);  
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.