Good day!

When working with a set there was an incomprehensible problem to me. I am required to wrap the whole set in one item. for example, you need to wrap all input type="radio" div element. I am writing the following:

jQuery code:

 $(function(){ var form = $('form').children(); form.each(function(n){ if($(this).is(':radio') $(':radio').wrapAll('<div class="radios"></div'); }); }); 

And, it seems, there should be happiness - all radio elements should turn around with a common div element. Annette! in the DOM see the following:

DOM :

 <div class="radios"> <div class="radios"> <input type="radio" name="choise" value="yes"/>Yes <input type="radio" name="choise" value="no"/>No </div> </div> 

I can't figure out where the external div comes from. Tell me please!

Amendment!!! You cannot leave the loop bypass!))

    2 answers 2

    no wonder, since you execute .wrapAll() with each iteration of the .each() loop. I can offer this option:

     $(function(){ var form = $('form').children(); var flag = true; form.each(function(n){ if(!$(this).is(':radio'){ flag = false; return; } }); if(flag){ $(':radio', $('form')).wrapAll('<div class="radios"></div'); } }); 

      @Spectre , your answer is correct with a small amendment! This is really an entry problem. But you propose to leave the cycle, and this is not exactly what is needed. It is my fault, I did not clarify this important point in the question. Therefore, you have a plus, but I offer my solution:

      jQuery code

       $(function(){ var form = $('form').children(), radio_founded = false; $(form).each(function(n){ if($(this).is(':radio')&&!radio_founded) { radio_founded = true; $(':radio').wrapAll('<div class="radios"></div>); } }); }); 
      • exactly the task at hand is the key to the success of its implementation =) - Specter
      • =) that's right. Only now as a question to close =) - LeD4eG
      • there is a question to close the button, specify the reason and everything - Specter
      • it is different) moral dilemma so to speak)) ok, you have to be completely honest! I will accept your answer. and those who will then read it let them choose which answer is correct. - LeD4eG