How to catch element by Jquery id?

Asked

Viewed 1,177 times

0

I have the following HTML code generated by PHP:

<li id="15" data-status="Em Processo" class="list-group-item tasks-list-group">
    <p style="display: none">#15</p>                                                                            
    <span class="badge" style="background-color:#67A6DF">Processo</span>                                    
    08/12/2016<br>
    Teste 2                                     
    <p style="display: none">Média</p>
    <p class="fantasy">Teste</p>
    <div class="type-average"></div>
    <i class="fa fa-flask fa-lg test-task" aria-hidden="true"></i>                                  
    <i class="fa fa-times fa-lg cancel-task" aria-hidden="true"></i>
</li>

When I click on <i class="fa fa-flask fa-lg test-task" aria-hidden="true"></i> it must change the status of the task to Testing.

But I need to get the tag ID li, but I can’t take it for .parent(), because the sequence of HTML elements changes.

But I tried the following:

$(".test-task").on('click', function(){
    var element = $(this).find('.tasks-list-group').attr('id');    
    var idTask = $(element).val();   
    alert(idTask);  
});

But returns undefined.

Does anyone have any idea what I can do?

  • 1

    It is returning undefined because its element variable brings a string with the name of the ID. However, the jquery selector needs "#" + id. That is $("#" + element). val();

  • 1

    You can also use the Closest. Inside the click function on . test-task. var idTask = $(this). Closest("li"). attr("id").

1 answer

1


You can pick up by . parents() regardless of the order and quantity of elements. As long as the father is always a li:

var $parent = $(this).parents('li');

https://api.jquery.com/parents/

Browser other questions tagged

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