Reputation: 43
I want to create HTML elements like this
<div>
<span class="u-label"></span>
<span class="u-title"></span>
<span class="u-info"></span>
</div>
I use javascript code$('div').append(Array(3).fill($('<span>test</span>')).map((el, index) => el.addClass(['u-label', 'u-title', 'u-info'][index])));
However,it doesn't work.It only returns <div><span class="u-label u-title u-info">test</span></div>
https://jsfiddle.net/paq8tdfL/
Upvotes: 0
Views: 564
Reputation: 8423
This also works:
$('div').append(Array(3).fill().map((el, index) => $('<span>test</span>').addClass(['u-label','u-title','u-info'][index])));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
Your problem is that $('<span>test</span>')
is added 3 times to the array, it's the same reference. So when you do .addClass()
and .append()
you're working on the same span
element.
Upvotes: 1
Reputation: 2417
$('ul').append(Array.from(new Array(3)).map(x => $('<li>test</li>')).map((el, index)=>el.addClass(['u-label','u-title','u-info'][index])));
Upvotes: 0
Reputation: 11480
Adding the classes in an array
and looping through the array
using a for
loop can be a much cleaner and more readable approach:
var arr = ['u-label', 'u-title', 'u-info'];
for(var i = 0; i< arr.length; i++){
$('div').append('<span class="' + arr[i] + '">test</span><br />');
}
.u-label{
color: #F00;
}
.u-title{
color: #1e8c55;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>
Upvotes: 0