How can I check if two / div elements 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 check if the checkbox that was set by the user is checked and the button they clicked on belongs to the same parent element and then shows the div

Any help would be greatly appreciated. thanks

+4
source share
4 answers

You need to compare the levelListID that you requested correctly with the flag identifier of the closest parent you should request in the same way:

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

This should work:

 //compares the parent() HTMLElement (not the jQuery object) if ( $(this).parent().get(0) == $('input.cartLevelChecked:checked').parent().get(0) ) { $(".selectPlan").show(); } 
+2
source

you were almost there, this should work if the parent is the immediate parent of both cardID and checkBoxID:

 if($('#'+cartID).parent().attr(id) == levelListID && $('#'+checkboxID).parent().attr(id) == levelListID ) { $(".selectPlan").show(); } 
0
source

You can simply go to the parent <li> element and see if the checkbox exists there, for example:

 $('.addtoCart').click(function() { if($(this).closest('li').find('input.cartLevelChecked:checked').length) { //yes we're in the same parent } }); 

This uses .closest() to navigate to the parent <li> and then peek inside for the checkbox using .find() . Then we just check that .length not 0 ( true ), which means it is found alone.

0
source

All Articles