Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ID value of first element with specific class in html by jQuery

I have this HTML code:

    <div id="calc_pol_list">
       <li class="calc_li">
           <span class="right_list_number">1</span>
           <p id="120" class="calc_p"/>
       </li>
       <li class="calc_li">
           <span class="right_list_number">2</span>
           <p id="100" class="calc_p"/>
       </li>
    </div>

I need to get ID of first p: with jQuery and convert this ID to string.

I've tried this code:

    $('#calc_pol_list p:first').attr('id');

But it doesn't works.

How can I do this?

UPDATE: Here is my function:

function refreshCost(){
    if ( jQuery.isReady ) {
        stomCost = parseInt($('div#calc_pol_list calc_p:first').attr('id'));
        var cost = stomCost + scatCost + polCost;               
        $("#pre_cost").text(cost);
    };
};

Yes, my code is correct, if considered separately from the rest of the code. I realized what the problem is, but I do not know how to solve it. The problem is that these

I add after the Ajax request that is not in their original DOM. The form, which owns these

is inside the div. I read here that I need to make the form a direct child of the body, but in this case it's impossible.

like image 448
Shadow_ Avatar asked Dec 25 '22 19:12

Shadow_


1 Answers

$('#calc_pol_list p').first().attr('id')

like this :)

like image 127
MAQU Avatar answered Dec 28 '22 08:12

MAQU