Wrap and add an array element using jQuery.each

I ruin myself because of this. Not necessarily an experienced ind. But should this just be true?

I want to wrap every element in my 'arr' -array in <div class="mongol"></div> and add it to div#testBox . I use jQuery.each for this, but I get nothing:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type='text/javascript'> var arr = ["one", "two", "three", "four", "five"] jQuery.each(arr, function() { $(this).append("#testBox").wrap("<div class='mongol'></div>"); }); </script> 

If I alert(this) in my jQuery.each function, then it warns every element just fine. I do not understand

What I'm trying to achieve:

 <div id="testBox> <div class=" mongol ">one</div> <div class="mongol ">two</div> <div class="mongol ">three</div> <div class="mongol ">four</div> <div class="mongol ">five</div> </div> 
+4
source share
2 answers
 var arr = [ "one", "two", "three", "four", "five" ] jQuery.each(arr, function(index, value) { $("#testBox").append("<div class='mongol'>" + value + '</div>'); }); 

This works if you have a <div> like on your site

 <div id="testBox"></div> 
+4
source

Are you confusing append () with appendTo () ? The code you submitted will add a testBox element to each of your array elements, which is probably not what you want (and will not work anyway). Try:

 jQuery.each(arr, function(index, item) { jQuery("<div class='mongol'></div>").text(item).appendTo("#testBox"); }); 
+7
source

Source: https://habr.com/ru/post/1339815/


All Articles