Reputation: 29116
I have a function that returns a list of HTML elements to be added to another tag. This function is meant to be called as follow:
$('#somewhere').append(getElements())
To test the feasibility I wrote this:
var el = $()
for (u in ['foo', 'bar']) {
el.append($('<li>').addClass(u).text(u + 'Text'))
}
$('<ul>').append(el).html()
Eventually I get nothing into <ul>
. Why? Where is my mistake? I suspect the $()
to not work as wanted because if I do var el = $('<div>')
instead, then it works.
Note
I could have used:
getElementsInto('#somewhere')
But I would prefer:
$('#somewhere').append(getElements())
Upvotes: 2
Views: 468
Reputation: 1075009
append
appends the given elements to every element in the jQuery set you call it on. $()
is an empty jQuery set, so append
on it is a no-op. There are no elements to append to. (Also note that you're using the wrong style of loop to loop through an array; in your loop, u
will be "0"
and then "1"
.) Also, calling .html()
without using the return value is a no-op.
add
would create a new jQuery object with the additions:
var elements = $();
['foo', 'bar'].forEach(function(u) {
elements = elements.add($('<li>').addClass(u).text(u + 'Text'));
});
var ul = $('<ul>').append(elements);
// then append `ul` somewhere...
ul.appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
...but I think I'd build up the elements in an array. In your case, since your starting point is an array, you can use map
:
var elements = ['foo', 'bar'].map(function(u) {
return $('<li>').addClass(u).text(u + 'Text');
});
var ul = $('<ul>').append(elements);
// then append `ul` somewhere...
ul.appendTo(document.body);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Upvotes: 4