Check value in all child divs of specific parent div

In my project. I am trying to check if an already defined number is present in any other neighboring div that is present in the parent div.

  //generated dynamically using jQuery <div> //parent div //many div's //one of the child div is selected by the user. </div> <div> //another parent div //my function is checking one of these div instead of the above, rarely </div> 

I used the code below. but sometimes (rarely) another parent div is selected which I don't want to check (I checked with a debugger in chrome). and sometimes, even if the function selects the correct parent div, it always selects the same child div as the user selected.

JQuery

 function checkInGroup(){ var selectedDiv = $('#' + _selectedDivId); //updated after engineer comment selectedDiv.parent("div").children().each(function(){ debugger; if(this !== selectedDiv[0]){ //selecting the same div var self = $(this); if(self.text() == _randomNumber){ debugger; //never executing //do some function here } } }); } 

EDIT: I'm not sure why my code is not working when it works fine in jsbin , I need to check why. Is it always a check with the same user selected div? Therefore, the function is not included in the if statement.

debugger that is present inside the if statement is never executed. and also each function loop happens only once with the same div selected (therefore, the function is not included in the if statement)

Here is jsfiddle

+4
source share
4 answers

Use siblings .

 $('#' + _selectedDivId).siblings().each(function(){ }); 

Updated:

The selectedDiv id is not really a button id. what a problem. please change your code as below.

  selectedDiv.parent("div").parent("div").find("button").each(function(){ 

demo

+1
source

to try:

  selectedDiv.parent("div").children().not(selectedDiv).each(function(){ //your code }); 
+2
source

The $ .each () function has a valid $ .each ([Array], index, element) signature. In your case:

 function checkInGroup(){ var selectedDiv = $('#' + _selectedDivId); $.each(selectedDiv.parent("div").children(), function(index, element){ debugger; if($(element) !== selectedDiv){ //selecting the same div if($(element).text() == _randomNumber){ //do some function here } } }); } 
+2
source

selectedDiv may be an array in your example.

I do not think you can compare two jQuery objects like this.

Can I use data attributes?

eg.

 var selectedDiv = $('#' + _selectedDivId); selectedDiv.data('selected', true); 

then

 selectedDiv.parent("div").children().each(function(){ debugger; if($(this).data('selected') !== true){ //selecting the same div if($(this).text() == _randomNumber){ //do some function here } } }); 

Just remember to set selected to false in the div when it is canceled.

There is probably a more efficient way to do this, but it should work.

0
source

All Articles