• Need help with jquery selector

    I have the following HTML:

    <ul class="someclass">
    <li id="1">
    <button type="button" class="grey"></button>
    </li>
    <li id="2">
    <button type="button" class="grey"></button>
    </li>
    <li id="44">
    <button type="button" class="grey"></button>
    </li>
    <li id="54">
    <button type="button" class="grey"></button>
    </li>
    </ul>
    

    Now here is what I am trying to accomplish using jquery:

    When the button is pressed to find out the idparent li, here is how I tried and failed:

    $(".grey").live('click', function(){
    alert($(this).parents("li").attr("id"));
    alert($(this).parents("li:first").attr("id"));
    });
    

    Both give me a nullwarning, how can I do this?

    UPDATE QUESTION

    Ah, yes, I forgot to mention that this button elementone is not entirely in the tag li, it was created on the fly, when liis hoveredit using append? I wrote this example so you can get idea what I'm trying

    OTHER UPDATE :

    When I try simply $(this).closest("li");, I get a message [object Object], but if I add attr("id");, I get null

    +3
    3

    , id: , . IIRC, Firefox , IE ( ). , : "item_44", .

    : http://www.w3.org/TR/html4/types.html

    ID NAME ([A-Za-z]), , ([0-9]), ( "-" ), ( "_" ), ( ":" ) ( "." ).

    +3

    . EDIT. Internet Explorer. , . , .

    - closest:

    $(this).closest('li')
    
    +2

    I don’t care, since you only travel one level up, you only need .parent (), not .parents () ... but best of all can be .closest () (you can read here here ).

    0
    source

    Source: https://habr.com/ru/post/1736888/


    All Articles