简体   繁体   中英

How to properly append li to ul using vanilla JavaScript and Firebase?

So I do want to get all of my messages in my firebase database console. My code is plain JavaScript.

HTML

<ul class="collection" id="chatList"></ul>

JS

var databaseRef = firebase.database().ref('messages');
var chatList = document.getElementById('chatList');
databaseRef.on('value', function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
      chatList.appendChild('<li class="collection-repeat">' + childSnapshot.val().message + '</li>');
  })
});

在此处输入图片说明

With my code, I only get the last value in the database because I guess it also appends the other <li> that is being generated inside the foreach.

What is the proper way to append <li> so that it won't also append the other <li> ?

I know that in jQuery, it can be achieved like this:

$('#chatList').append('<li class="collection-repeat">' + childSnapshot.val().message + '</li>')

Any help would be much appreciated.

appendChild() is used to append a node to an element. But you are trying to append a string .

Try using

var databaseRef = firebase.database().ref('messages');
var chatList = document.getElementById('chatList');
databaseRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
        var node = document.createElement("li");
        node.className="collection-repeat";
        var textnode = document.createTextNode( childSnapshot.val().message );
        node.appendChild(textnode);
        chatList.appendChild(node);
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM