Finding the id of a parent div using Jquery

前端 未结 9 1093
失恋的感觉
失恋的感觉 2020-11-29 17:00

I have some html like this:

Volume =

9条回答
  •  猫巷女王i
    2020-11-29 17:36

    To get the id of the parent div:

    $(buttonSelector).parents('div:eq(0)').attr('id');
    

    Also, you can refactor your code quite a bit:

    $('button').click( function() {
     var correct = Number($(this).attr('rel'));
     validate(Number($(this).siblings('input').val()), correct);
     $(this).parents('div:eq(0)').html(feedback);
    });
    

    Now there is no need for a button-class

    explanation
    eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
    $(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
    $(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
    Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.

    You should have a look at the jQuery docs, particularly selectors and traversing:

    • http://docs.jquery.com/
    • http://docs.jquery.com/Selectors
    • http://docs.jquery.com/Traversing

提交回复
热议问题