Reputation: 14854
I have an array of users which I'd like to add to a ul
list . The code works fine when I add users to the list as li
elements:
users = ['Bob','Mary', 'Mike']
var ul = $('<ul></ul>');
users.forEach(function (user) {
ul.append($('<li><strong><strong></li>').text(user));
});
$('#users').html(ul);
But what I want is to add users as hyperlinked texts so that thay can be clicked, so for example I'd like Bob
to be rendred as:
<li><strong><a href='#' id="Bob">Bob</a><strong></li>
But whatever I tried I could not append the a
elements to ul
as above. Appreciate your help.
Upvotes: 1
Views: 814
Reputation: 10096
This seems like a good example to start using template strings, these are strings, you can easily add variables to:
users = ['Bob','Mary', 'Mike']
var ul = $('<ul></ul>');
users.forEach(function (user) {
ul.append($(`<li><strong><a href="#" id="${user}">${user}</a></strong></li>`));
});
$('#users').html(ul);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="users"></div>
Upvotes: 2
Reputation: 13666
You can just concatenate using the +
operator:
users = ['Bob','Mary', 'Mike']
var ul = $('<ul></ul>');
users.forEach(function (user) {
ul.append($('<li><strong><a href="#" id="' + user + '">' + user + '</a></strong></li>'));
});
$('#users').html(ul);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="users"></div>
Upvotes: 2