javascript - Compare element values and assign attribute to larger -


'ive been banging head trying figure out best way go this...

i have html:

<div id="aa1">23</div> <div id="a2">14</div>  <div id="b1">67</div> <div id="bb2">21</div> 

what attempting compare value of these elements in pairs. easiest solution be:

var a1 = parsefloat($("#aa1").text()).tofixed(2); var a2 = parsefloat($("#a2").text()).tofixed(2); var b1 = parsefloat($("#b1").text()).tofixed(2); var b2 = parsefloat($("#bb2").text()).tofixed(2);  if (a1 > a2){     $('#aa1').css('color','#fff'); }else{     $('#a2').css('color','#fff'); }  if (b1 > b2){     $('#b1').css('color','#fff'); }else{     $('#bb2').css('color','#fff'); } 

assuming div ids not same length, contain numbers, , there multiple pairs, although pairing same (always a1/a2, b1/b2, etc), best way go this? ive tried few different solutions (substring, regex, math.max), hit different roadblock each.

edit:

john s set me in right direction. js ended using was:

//grabbing initial values.  yes, these assigned in next section. var a1 = parsefloat($("#aa1").text()).tofixed(2); var a2 = parsefloat($("#a2").text()).tofixed(2); var b1 = parsefloat($("#b1").text()).tofixed(2); var b2 = parsefloat($("#bb2").text()).tofixed(2);  //setting pairs.  note additional - character enable ability split correctly. var arr1 = ['aa1-'+a1, 'a2-'+a2]; var arr2 = ['b1-'+b1, 'bb2-'+b2]; //creating two-demensional array var mainarr = [arr1, arr2];  //loop through each pair in array (var i=0; < mainarr.length; i++){ //split off values want var first = mainarr[i][0].split('-')[1], second = mainarr[i][1].split('-')[1]; //split off html ids want var firstcss = '#'+mainarr[i][0].split('-')[0], secondcss = '.'+mainarr[i][1].split('-')[0]; //compare pairs , assign correct attribute element. ((first > second) ? $(firstcss) : $(secondcss)).css('background-color','#dbffdb'); } 

still have setup pairs, way better million if/else statements.

could loop through elements 2 @ time:

function value($div) {     return parsefloat($div.text()).tofixed(2); }  var $divs = $('div'); // use whatever selector gets desired elements (var = 0; < $divs.length; += 2) {     var $div1 = $divs[i], $div2 = $divs[i + 1];     ((value($div1) > value($div2)) ? $div1 : $div2).css('color','#fff'); } 

Comments

Popular posts from this blog

java - Could not locate OpenAL library -

node.js - How to mock a third-party api calls in the backend -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -