Reputation: 451
There is dynamic data that needs to be looped and create list items.
I am creating HTML element via JQuery and inserting it in HTML. Below is the code
Dynamic Data:
dynamicData = ["qqq","www","eee","rrr","ttt","yyy","uuu","iii"]
HTML:
<ul class="test-list"></ul>
JS:
fnData: function (dynamicData) {
var ele = $('<li/>', {
class: 'item',
append:
'<a href="javascript:void(0)" class="link">click</a>'
});
var htmlData = dynamicData.map((item, index) => {
return ele;
});
$('.test-list').html(htmlData);
}
When fnData
function is triggered <li>
element is created and using map
looping trough the dynamic data.
After looping is complete htmlData
has length of 8 and when $('.test-list').html(htmlData);
is completed.
Only one <li>
element appears in the browser output
Not sure why it does not show all 8 <li>
items
Upvotes: 0
Views: 37
Reputation: 781068
You're returning the same element each time through the loop. An element can only be at one place in the DOM at a time.
You need to create a new element each time. So create the element inside the loop.
fnData: function (dynamicData) {
var htmlData = dynamicData.map((item, index) => {
return $('<li/>', {
class: 'item',
html:
'<a href="javascript:void(0)" class="link">click</a>'
});
});
$('.test-list').html(htmlData);
}
Upvotes: 2