Reputation: 41842
In my project. I am trying to check whether a certain number already present in any other adjacent div
's which are present in a 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's instead of the above, rarely
</div>
I used the following below code. but it sometimes(rarely) selecting the another parent div
's child elements which I dont want to check for (I checked with debugger in chrome). and if sometimes even if the function selects the correct parent div it is always selecting the same child div element which is selected by the user.
jQuery
function checkInGroup(){
var selectedDiv = $('#' + _selectedDivId); //updated after engineer's 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 am not sure why my code is not working when it is working fine in jsbin. I need to check why so.. It is always checking with the same user selected div?? Hence the function is not entering into the if statement..
The debugger
which is present inside the if statement is never executing. and also the each function loop is happening only once with the same selected div (hence the function is not entering in to the if statement)
Here is the jsfiddle
Upvotes: 4
Views: 309
Reputation: 2281
Use siblings .
$('#' + _selectedDivId).siblings().each(function(){
});
Updated:
selectedDiv id is not actually div it is button id. that's the problem. please change your code like below.
selectedDiv.parent("div").parent("div").find("button").each(function(){
Upvotes: 1
Reputation: 8524
try:
selectedDiv.parent("div").children().not(selectedDiv).each(function(){
//your code
});
Upvotes: 2
Reputation: 96
The $.each() function has an actual signature of $.each([Array], index, element). 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
}
}
});
}
Upvotes: 2
Reputation: 2488
selectedDiv
may be an array in your example.
I don't think you can compare two jQuery objects like this.
You could consider using data attributes?
e.g.
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 on the div when it's deselected.
There's probably a more efficient way to do this but this should work.
Upvotes: 0