Compare Div Value

2

You can sweep a div and return it. For example:

<div class='result' id='add9' align='middle'> 1</div>
<div class='result' id='add9' align='middle'> 2</div>
<div class='result' id='add9' align='middle'> 3</div>

We have a div with a value of 1, value2 and value 3. Below, you have this syntax via jquery:

$( "td" ).find( "div" );

This syntax sweeps the DIV and does something with it. Can I after "sweep" the div, make a comparison of the returned values? Using as an example the above values: 1, 2, and 3?

Thank you.

    
asked by anonymous 31.03.2017 / 23:08

1 answer

1

Yes you can. With $('td').find('div'); you have a collection with the elements, and to have an array / collection with your values you can do this:

var valores = els.get().map(function(el) {
  return Number(el.innerHTML.trim());
});

Examples:

Use the numbers to compare them:

var els = $("td").find("div");
var valores = els.get().map(function(el) {
  return Number(el.innerHTML.trim());
});

console.log(valores);
console.log('o primeiro valor é', valores[0] > valores[1] ? 'maior' : 'menor');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td><divclass='result'id='add9'align='middle'>1</div><divclass='result'id='add9'align='middle'>2</div><divclass='result'id='add9'align='middle'>3</div></td></tr></table>

Usethenumberstochangeattributes/characteristicsintheDOM

var els = $("td").find("div");
var valores = els.get().forEach(function(el) {
var nr = el.innerHTML.trim()
  if (nr == '1') el.style.color = 'purple';
  if (nr == '2') el.style.color = 'red';
  if (nr == '3') el.style.backgroundColor = 'lightblue';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <div class='result' id='add9' align='middle'> 1</div>
      <div class='result' id='add9' align='middle'> 2</div>
      <div class='result' id='add9' align='middle'> 3</div>
    </td>
  </tr>
</table>
    
31.03.2017 / 23:14