2

I've added the whole loop. This is further included in another loop. var divid=1; is defined before the loop starts and is incremented on each iteration. The console.log in the if else condition works. $('[id^="d"]').css("background-color","#43A942"); changes the css of ALL the elements in the whole page (!) whose ids starts with a 'd' but I want to make the changes only to elements in the loop. Is there any other way?

var 'util' equals 95 in this case

$(uname.weeklyData).each(function(i1,weekno){
    var util=weekno.TotalUtilization;

    trHTML += '<td id="'+tnum +'"><div style="background-color: rgb(255, 255, 255);"><div id="d'+divid +'" style="height: 20px; color: rgb(0, 0, 0); font-weight: bold;padding-left: 4px;width:'+util +'%;">' + weekno.TotalUtilization +'</div></div></td>';//displays TotalUtilization
    if(util<=50){   
        $('[id^="d"]').css("background-color","#E9691E");   //orange
    }
    else if(util>50 && util<=80){   
        $('[id^="d"]').css("background-color","#049FD9");       //blue
    }
    else if(util>80 && util<=100){
        $('[id^="d"]').css("background-color","#43A942");       //green
        console.log("check");
    }
    else if(util>100){
        $('[id^="d"]').css("background-color","#EBEBEC");   //gray
    }
    tnum=tnum+1;
    divid=divid+1;

});

I am trying to append HTML rows to a table dynamically. I've given the ids for the div as d1,d2,d3...etc. How do I access that id to change that particular div's background color using JQuery?

When I explicitly type

$('#d185').css("background-color","#43A942");

The background color changes to green. But how to do this using the variable divid in JQuery?I am new to coding and am unsure about the syntax, all the help is appreciated.

  • All [**CSS Selectors**](https://www.w3schools.com/cssref/css_selectors.asp)! – ibrahim mahrir Apr 04 '17 at 18:47
  • _But how to do this using ids in JQuery?_ Well, you're already doing it using IDs, so where is the problem? – ibrahim mahrir Apr 04 '17 at 18:49
  • I sense it has something to do with this: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example! – ibrahim mahrir Apr 04 '17 at 19:01
  • I think i worded the question incorrectly, i apologize. I want to use the variable 'divid' to change the css of that particular div. `$("#d" + divid).css("background-color","#43A942");` This doesnt work and `$('[id^="d"]').css("background-color","#43A942");` changes the css of all the elements with ids starting with a 'd'. @ibrahimmahrir –  Apr 04 '17 at 19:11
  • Can you provide more code (the loop) and where are you calling `$("#d" + divid)...`. It's as I said probably a problem of closures inside loops or something like that! – ibrahim mahrir Apr 04 '17 at 19:15
  • Sure @ibrahimmahrir i've added more code! –  Apr 04 '17 at 19:26
  • You still havent revealed the mysterious `divid`! – ibrahim mahrir Apr 04 '17 at 19:31
  • Plus you can't select them they're not in the DOM yet! You'll have to decide which color to use and then add it to the html! I'll post an answer to explain more! – ibrahim mahrir Apr 04 '17 at 19:33
  • I've posted an answer bellow! I hope it fixes your problem! – ibrahim mahrir Apr 04 '17 at 19:42
  • You were a big help! Thanks a ton :) –  Apr 04 '17 at 19:52

6 Answers6

1

You could use attribute starts With selector.

$('[id^="d"]').css("background-color","#43A942");

which selects all the elements whose id starts with d

The best thing to do is, instead of using id starts with assign a class to the div instead and define your classes in your CSS. That would make things lot easier. The way it works now, based on your code, the last util in the loop will be used to target the background color.

JS

$(uname.weeklyData).each(function(i1, weekno) {
  var util = weekno.TotalUtilization;
  var className = '';

  if (util <= 50) {
    className = 'orange';
  } else if (util > 50 && util <= 80) {
    className = 'blue';
  } else if (util > 80 && util <= 100) {
    className = 'green';
    console.log("check");
  } else if (util > 100) {
    className = 'gray';
  }

  trHTML += '<td id="' + tnum + '"><div style="background-color: rgb(255, 255, 255);"><div id="d' + divid + '" class="' + className + '" style="height: 20px; color: rgb(0, 0, 0); font-weight: bold;padding-left: 4px;width:' + util + '%;">' + weekno.TotalUtilization + '</div></div></td>'; //displays TotalUtilization

  tnum = tnum + 1;
  divid = divid + 1;

});
trHTML += '</tr>';
$("#myTable tbody").append(trHTML);

CSS

.orange {
  background-color: #E9691E;
}

.blue {
  background-color: #049FD9;
}

.green {
  background-color: #43A942;
}

.gray {
  background-color: #EBEBEC;
}
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • This has not worked for me. Can you please tell me what changes should i make in this line to make it work? `$("#d" + divid).css("background-color","#43A942");` @Sushanth -- –  Apr 04 '17 at 18:51
  • @AyushiZile You need to make sure you are calling this method in document ready, if you want this to happen when the page loads. If you are building this on the fly, then you will have to call this after you insert it into the `HTML` – Sushanth -- Apr 04 '17 at 18:54
  • @AyushiZile What is the value of `divid`? And is this called in a loop or not? – ibrahim mahrir Apr 04 '17 at 19:00
  • This has worked for me ! Thanks! This part of code is included in a loop.But there is one minor problem as it selects all the ids in the page which starts with 'd' and changes its bcolor instead of seaching only in that particular loop. –  Apr 04 '17 at 19:02
  • Yes it is included in a loop... and 'divid' increments on each iteration of the loop. @ibrahimmahrir –  Apr 04 '17 at 19:05
1

I dont quite understand but maybe you need:

$('#d'+i).css("background-color","#43A942");

Where i is inside a for (for an id).
For example:

for(var i=0;i<some_length;i++){
    $('#d'+i).css("background-color","#43A942");
}

This is called dynamic id... google it for more examples, its the one of the most important things on jquery.

Konstantinos
  • 943
  • 1
  • 9
  • 20
0

If you have the id's in an Array (say variable ids) then you can do:

ids.forEach(id => $(`#d${id}`).css("background-color","#43A942"))

This iterates through the list of all ids and for each id it runs the jQuery line to color them green.

Note: If you need ES5 (Older Browsers) compatibility, you can do:

ids.forEach(function(id) {
    $('#d'+id).css("background-color","#43A942")
})
AP.
  • 8,082
  • 2
  • 24
  • 33
0

Sorry if I'm missing what you're asking.

From what I can tell, you are using ids with jQuery.

Any $() is actually calling a jQuery method.

In this case, you're using $('#id') which uses CSS Selectors (as mentioned in the comments) to reference DOM elements.

Your line $('#d185').css("background-color","#43A942"); is actually jQuery for the vanilla javascript line:

document.getElementById('d185').style.backgroundColor = "#43A942";

Edit: Going a little deeper into the CSS selectors, when you use $('#id') the # in the string is tells jQuery to search for an id on the page, if you were to do something like $('.class') would then select ALL elements on the page where in the HTML they would have a class named... class (i.e. <div class="class"></div>) and so one as per how CSS selectors are defined.

This is one of the many benefits that jQuery has to offer: it shortens the amount of bytes needed to describe common actions with JavaScript in an attempt to make it faster to load a webpage (every byte counts!).

Patrick Barr
  • 1,123
  • 7
  • 17
0

Styling all elements with an id starting with d

It would be unwise and with an unsatisfactory performance to style all those DOM elements separately, instead of creating one rule for all of them. Here is plain, purist, vanilla JS way (jQuery would neither look nor especially perform better in this case, anyway):

document.styleSheets[0].insertRule('[id^="d"] { background-color: #43A942;}');

, where [id^="d"] is "starts with" CSS selector. That way you can style all DOM elements with IDs starting with d.

Styling group of elements

Best way

If this is not what you want, because say you want to style only some elements with the ids starting with d, it would be best to give them all a particular class and use above code analogically:

document.styleSheets[0].insertRule('.someClass { background-color: #43A942;}');

Last resort way

If you can't or don't want to give all elements of your interest particular class, you could just iterate through the array of all those elements. This is how to do it elegantly with ES6:

const array = [element1, element2, element3]; // Dummy elements
array.forEach(element => element.style.backgroundColor = '#43A942');
Community
  • 1
  • 1
Przemek
  • 3,855
  • 2
  • 25
  • 33
0

You are generating a string that represent the html that will be appended to the DOM later when the loop is exited, so throughout the itterations of the loop, the elements you are trying to select using $("#d" + divid) are not yet appended (they don't exist just yet) so nothing will be selected and nothing will be changed. So you either have to wait untill they're appended, or just add the color directly to the html string like this:

$(uname.weeklyData).each(function(i1,weekno){
    var util=weekno.TotalUtilization;

    // first decide what the color is going to be
    var color = "rgb(255, 255, 255)"; // default value
    if(util <= 50)
        color = "#E9691E";
    else if(util > 50 && util <= 80)
        color = "#049FD9";
    else if(util > 80 && util <= 100)
        color = "#43A942";
    else if(util > 100)
        color = "#EBEBEC";

    // then add it to the HTML
    trHTML += '<td id="'+tnum +'"><div style="background-color: ' + color + '"><div id="d'+divid +'" style="height: 20px; color: rgb(0, 0, 0); font-weight: bold;padding-left: 4px;width:'+util +'%;">' + weekno.TotalUtilization +'</div></div></td>';
    //                                                      here ^^^^^^^^^^^

    tnum++;
    divid++;
});
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • This worked as a charm! Thanks so much! :D The mistake I was making like you said, was that the elements I wanted to append the css to, did not exist at all! So no changes were displayed! I did not need the mysterious 'divid' at all to make this work thanks to you ;) –  Apr 04 '17 at 19:51