The first thing we're going to do is create a list item, and we're going to do this once again using jQuery. We're going to make a variable, this variable is going to be called li, and we're going to go ahead and use jQuery slightly differently:
socket.on('newMessage', function (message) {
console.log('newMessage', message);
var li = jQuery();
});
Rather than using jQuery to select an element, we're going to use jQuery to create an element, then we can modify that element and add it into the markup, making it visible. Inside quotes, we're going to open and close an li tag, just like we would inside index.html:
socket.on('newMessage', function (message) {
console.log('newMessage', message);
var li = jQuery('<li></li>');
});
Now that we have this in place we have to go ahead and set its text property, I'm going to set li.text, by calling li.text with the value I want to use.
In this case the text is going to require us to set up a little template string, inside the template string we are going to go ahead and use the data that comes back. For now we're going to use the from attribute and the text attribute. Let's get started with who it's from, then we'll add a little colon and a space to separate that from the actual message, and finally, we'll inject message.text at the end:
var li = jQuery('<li></li>');
li.text(`${message.from}: ${message.text}`);
Now at this point we've created an element but we haven't rendered it to the DOM. What we're going to do is use jQuery to select that brand new element we created, we gave it an ID of messages, and we're going to append something to it by calling the append method:
var li = jQuery('<li></li>');
li.text(`${message.from}: ${message.text}`);
jQuery('#messeges').append
This is going to add it as its last child, so there's already three items in the list; the newest one will show up below those three as the fourth item in our ordered list. All we have to do is call append as a function, passing in our list item:
var li = jQuery('<li></li>');
li.text(`${message.from}: ${message.text}`);
jQuery('#messeges').append(li);
});
And with this in place we are done. Now if you're not familiar with jQuery this can be a bit overwhelming, but I promise the techniques we use here we'll be using throughout the book. By the end, you'll be much more comfortable selecting and creating elements.