1

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?

1
  • And the problem is? Create the li, add the classes (.addClass()), add the id (.attr()), add the text (.text()/.html()) and append to the list (.appendTo()) Commented Jun 27, 2017 at 5:46

3 Answers 3

3

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')
;
Sign up to request clarification or add additional context in comments.

Comments

2

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')

Comments

0

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);

}

1 Comment

Thank you for the reply :) +1 from me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.