Search code examples
jqueryhtmlformsdom-traversal

How can I check if two elements/div belong to the same parent?


Hi I am working on this piece of code for a shopping cart

$('.addtoCart').click(function() {

    //get button id      
    var cartID = $(this).attr("id"); 

    //get check box id   
    var checkBoxID = $('input.cartLevelChecked:checked').attr("id");

    //get parent id
    var levelListID = $(this).closest('li').attr("id");

    if(('#'+cartID && '#'+checkBoxID).parent('#'+levelListID)){
        $(".selectPlan").show();
    }

    //alert(/*cartID + checkBoxID +*/ levelListID);
});

Basically I'm checking to see if the check-box the user checked and button they clicked on belongs to the same parent then show a div

any help would be greatly appreciated. thanks


Solution

  • You need to compare levelListID, which you correctly queried, to the id of the checkbox's closest li parent, which you should query the same way:

    if (levelListID === $('#' + checkBoxID).closest('li').attr('id')) {
        ...
    }