0

    // Client
function elemToString(elem){
    return elem.outerHTML
}

let child = document.createElement("div")
child.textContent = "foo"
child.className = "messages"
parent.appendChild(child)
socket.emit('chatMsg', elemToString(child))

//Server
const messages = []

socket.on('chatMsg', elem => {
  messages.push(elem)
})

I have a button that creates a div with content, how can i display newly appended divs to everyone and not just the individual client.

Alexa Jenasoba
  • 93
  • 1
  • 1
  • 6

1 Answers1

0

The child variable is an object. When the same is written on network, it will become something like [object object].

All you need to do is to convert the DOMElement as string & send it via socket. Similarly, when the same is received, it is received as string. You will need to convert the string back in to DOMElement in order to append it into the document.

Refer here to know how to convert a DOMElement to string.

Refer here to know how to convert a string to DOMElement.

Basically, your code will need to changed like this:

// Client
    let child = document.createElement("div")
    child.textContent = `foo`
    child.className = "messages"
    parent.appendChild(child)

    socket.emit('newDiv', domElementToString(child))

function domElementToString(element) {...}

// Server
    socket.on('newDiv' elem => {
      // show newly appended divs
    })


Update:


// if "messages" are array of DOM elements, then the following will work

function stringToDOMElement(string) {...refer the 2nd reference link...}

socket.on('chatMsg', (elem) => {
  messages.push(stringToDOMElement(elem))
})
explorer
  • 944
  • 8
  • 18