0

I'm trying to add this array to the DOM, with each string element as part of an unordered list. Below I try to set message[i] = the element of the array I want to append to the list, but it doesn't appear to be working. Fetch new is an callback function that gets an array of strings as it's input FYI. Basically I am trying to display each element in that array at the bottom of the ul. ul class="messages" fyi. Is there something wrong with the way I am assigning the variable value?

   function fetchNew() {
        var PrintChat = function (Chat_Messages) {
        var y = Chat_Messages.length;
        for (i = 0; i < y; i++) {

            var message[i] = $('<li>Chat_Messages[i]<li>');
            $('.messages').append(message[i]);

        }
    }

2 Answers 2

1

I'm guessing it's literally outputting Chat_Messages[i] repeatedly?

You kind of have to tell JavaScript that it's a variable to be concatenated. Try this:

$(".messages").append("<li>"+Chat_Messages[i]+"</li>");

Note that for safety reasons you should ensure that the message is properly escaped, or better yet use native DOM methods like createTextNode(Chat_Messages[i]) to protect your site from XSS attacks.

Sign up to request clarification or add additional context in comments.

Comments

0

if fetchNew is a callback that gets an array of string, you're actually complicating it too much, a simpler method would be like so:

function fetchNew(myArray) {                           // receive the array as a parameter.
    var length = myArray.length;                       // Cache the length of array
    for (i = 0; i < length; i++) {                     // loop through the array.
        var element = $('<li>' + myArray[i] + '<li>'); // concatenate the current value inside an LI and create a dom element.
        $('.messages').append(element);                // Add element to the parent container
    }
}

Comments

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.