Reputation: 23025
Please check the below JavaScript code
<script>
function dynamicMessageLoader(id) {
$.get("SentMessagesDynamicLoaderServlet?idMessageGroup=" + id, function (responseJson) {
$('#li_list').empty();
var array = [];
$.each(responseJson, function (index, item)
{
array[index] = item;
});
$('#message_count').empty();
var readArray = array.length;
var count = readArray + " Messages Selected";
$('<p />', {html: count}).appendTo('#message_count');
for (var i = 0; i < readArray; i++) {
$('<li />', {html: array[i][0]}).appendTo('#li_list');
}
});
}
</script>
Then some HTML
<ul id="li_list"></ul>
In my JavaScript code, consider this section -
`$('<li />', {html: array[i][0]}).appendTo('#li_list');`
What I want is not to just create a <li>
but with its remaining attributes, exactly like below
<li class='clickable-row hand' id="3" >Text here</li>
In my array, array[i][0]
contains the ID and array[i][1]
contains a text. How can I achieve this?
Upvotes: 1
Views: 2019
Reputation: 133403
You were on correct path,
$('<li />', {
"id": array[i][0],
"text" : array[i][1],
"class" : 'clickable-row hand'
}).appendTo('#li_list');
OR, Create a object then use various method to manipulate element.
var li = $('<li />');
li.attr("id", array[i][0]);
li.text(array[i][1]);
li.addClass("id", 'clickable-row hand');
li.appendTo('#li_list')
Upvotes: 2
Reputation: 43451
It would be $('<li>', {html: array[i][1], 'class': 'clickable-row hand', id: array[i][0]})
Please note, that attributes may be without quotes, except class
that is reserved word.
Alternative
var li = $('<li>');
li
.addClass('clickable-row hand')
.text(array[i][1])
.attr('id', array[i][0])
.appendTo('#li_list')
;
Upvotes: 3
Reputation: 5546
You could try like this. create li and add attr & text to it and append that li to #li_list
for (var i = 0; i < readArray; i++) {
var li = $('<li/>')
.attr('id', array[i][0])
.text(array[i][1]);
.addClass('clickable-row hand');
$("#li_list").append(li);
}
Upvotes: 0