0

In short, I have a string of 5-10 events I'm receiving from an external server that look like:

event: add
data: { "hostname":"name", "properties": {"info": "50"}}

event: add
data: { "hostname":"name2", "properties": {"info": "45"}}

event: add
data: { "hostname":"name3", "properties": {"info": "67"}}

etc, etc..

And I am processing them via EventSource JS like this:

var source = new EventSource("http://XXX.XXX.XXX.XXX:PORT/")
source.addEventListener('add', onAdd)

function onAdd(e) {
  var data = parse(e)

  var output = document.getElementById('append');
  var ele = document.createElement("div");
  var frag = document.createDocumentFragment();
  frag.appendChild(ele);
  ele.setAttribute("class", 'row sub-item');
  ele.innerHTML ="<ul>"
                +"<li>" + "<span id=name>" + data.hostname + "</span>" + "</li>"
                +"<li>" + "INFO: " + "<span id=info>" + data.properties.info + "</span>" + "</li>"
                +"</ul>"
                +"</div>"
  output.appendChild(frag);
}

This code successfully adds each div and the unordered list inside it onto the page.

My problem is that I have another set of future events like:

event: update
data: { "hostname":"name", "properties": {"info": "65"}}

event: update
data: { "hostname":"name2", "properties": {"info": "35"}}

event: update
data: { "hostname":"name3", "properties": {"info": "15"}}

etc..

and these come from the server and send the new info property every so often. I can't find a way to update the all the unique info properties by using span class (<span class="info") because if I sort by class it updates every single info property on the page with the same number (name1 45 name2 45 name3 45) and I can't use id (<span id="info") because then it will only update the first one since id is only supposed to be used once on your page.

I know there has to be a simple solution for this that I am overlooking. Thanks!

1 Answers1

0

You could use datasets by adding a data-id attribute to each span, and then update only matches.

You could also alter your id to info_45 etc, and get id for each span, and use regex to get the id cleanID = idFromSpan.match(/\d+/g)[0];

turbopipp
  • 1,245
  • 2
  • 14
  • 27
  • Thanks for your input. I was able to accomplish this by setting the span id to the data.id property and then replacing the content within the span by using document.getElementByID(data.id).innerHTML = data.properties.info; Thanks again for your help c: – KILLADELPHIA Mar 13 '16 at 02:38