简体   繁体   中英

How to check if elements in a page already exist using Javascript?

I am building a chat app using flask socketio. So I am trying to implement chat history, but the problem I run into is that whenever a new user connects, the app sends the new user the chat history, as well as to the old user, thus resulting in duplicated chat history for the old user. I've tried everything server side, but I think the only way is through Javascript client side. Is there any way that when Javascript gets the chat history, could I make JS first check if that messages don't already exist on the page, and then append them?

Here is a screenshot on what is happening. visual representation of what's happening

Code(Client-side Javascript)

  const socket = io.connect("http://127.0.0.1:5000");

socket.on('connect', function() {

  socket.emit('sync_messages', {
    dname: "{{dname}}"
  });

});

Code (Server-side Flask Socketio)

@socketio.on('sync_messages')
def handle_sync(data):
        socketio.emit('show_all_messages', messages)

Code (Client-side again)

socket.on('show_all_messages', function(data) {
 // console.log(data);
  len = data.length;
  for (i = 0; i < len; i++) {
    const newNode = document.createElement('div');
    newNode.innerHTML = data[i];
    document.getElementById('messages').appendChild(newNode);
  }

})

Really simple. You can any give any types of attribute to that element which you need to find and do

function checkElement(){
   if(document.querySelector(/*Selector*/)){
      return true;
   }
   else{return false;}
}

then just call this function when you need. document.querySelector in if statement will automatically look for you does html element exist or not

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