4

I'm destroying myself over this. Not the must experienced ind js. But this should be simple right?

I want to wrap each element in my 'arr'-array in <div class="mongol"></div> and append it to the div#testBox. Im using jQuery.each to do so, but I am not getting anything:

<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 alerts every element just fine. I don't get it.

What i am 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>

2 Answers 2

7

Are you confusing append() with appendTo()? The code you posted will append the testBox element to each of your array items, which is probably not what you want (and won't work anyway). Try:

jQuery.each(arr, function(index, item) {
    jQuery("<div class='mongol'></div>").text(item).appendTo("#testBox");
});
Sign up to request clarification or add additional context in comments.

5 Comments

This triggers an error: Uncaught TypeError: Object has no method 'appendTo' (?) But what about this? $(this).wrap("<div class='mongol'></div>").appendTo("#testBox");
@Jonas, strange, that should work. text() returns the jQuery object, so it should be possible to call appendTo() on the result. I'll investigate that. Also, I don't think your suggestion will work: $(this) will try to match elements whose tag name are the same as your array items (i.e. none).
Thats weird. I don't know if its the jquery.each-thing that does it. But my question has been answered now. Thanks alot for you help. Jonas :)
@Jonas, got it, this was remapped after the call to jQuery(). Using explicit parameters fixes it. Answer updated accordingly.
Yeah that did the trick :) Double solutions to a simple problem is twice as nice. Thank you
4
var arr = [ "one", "two", "three", "four", "five" ]
    jQuery.each(arr, function(index, value) {
    $("#testBox").append("<div class='mongol'>" + value + '</div>');
 });

That works if you have a <div> like that in your Site

<div id="testBox"></div>

3 Comments

Cool! Sorry about the console.log() :)
haha thats just fine. Didn't even knew i existed, so now i have another debugging-tool. 2 x thanks :)
Oh for debugging javascript always use console.log() and firebug otherwise you can't loop throw stuff and so on...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.