Question

I am trying to change the class of all div element with the id "led1" which resides in another div with the id 1.

<div class="MACHINE">
  <div id="1" class="HOST">EMPTY
    <div id="led1" class="LED"></div>
  </div>
</div>

I use the following code but it only change the text "EMPTY" and not the class. Below is a piece of my js file is use to change the class. For some reason it doesn't work...

I hope that someone can direct my into the right direction.

$.each(data, function(hst) {
    $.each(data[hst], function(key, value){
        var currClass =  $('#led'+ key).attr('class');
        switch(value)
        {
           case 'EMPTY': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break;
           case 'PROCESSING': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break;
           case 'FINISHED': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break;
           case 'REPLACE': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break;
         }
      });
   });
   },
   error: function() {
     alert('Ello');
     console.log("ERROR: show_host_status")     
   },
 });
},   
}
Was it helpful?

Solution

I see a problem.

 case 'EMPTY': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$('#' + key).html(value);break;

It sets the "HOST"'s HTML to whatever value is (thus removing the LED). Try something like this.

<div class="MACHINE">
    <div id="1" class="HOST">
        <div class='host-value'>EMPTY</div>
        <div id="led1" class="LED"></div>
    </div>
</div>

and your code in the case statements as

 case 'EMPTY': $('#led' + key).removeClass(currClass).addClass('LED ' + value);$(".host-value", $('#' + key)).html(value);break;

Then you have to change how your getting the "value" since its not just straight element its from #key .host-value

OTHER TIPS

As pointed out in other responses, the answer is technically:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

apologies to: @dgvid

Try changing <div id="1"> to <div id="host-1"> and update your script accordingly

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top