简体   繁体   中英

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.

What about this:

$('#calc_pol_list p').eq(0).attr('id');

jsfiddle http://jsfiddle.net/krasimir/ppzqx/1/

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

像这样 :)

Solution is to use .ajaxStop

$(document).ajaxStop(function() {
    alert($('#calc_pol_list p').eq(0).attr('id'));
});

Try this:

$(document).ready(function(){ 
alert($('#calc_pol_list p:first').attr('id'));
});

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

See: What are valid values for the id attribute in HTML?

Create a variable and get variable in it eg

var content = $('#calc_pol_list > li p:first').attr('id');

and alert it you will get id as string eg

alert (content );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM