Compare value of Div

Asked

Viewed 238 times

2

It is possible to scan a div and return its value. 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 value 1, value2 and value 3. Below, you have this syntax via jquery:

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

This syntax scans the DIV and does something with it. With you after "sweeping" the div, do a comparison of the returned values? Using as an example the values above: 1, 2, and 3?

Grateful.

1 answer

1


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

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

Examples:

Use numbers to compare numbers:

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>
      <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>

Use numbers to change attributes/features in the DOM

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>

  • I can for example set a color="red" if the value is equal to 2 for example? How could I do it? Grateful.

  • @user54154 yes, I added one more example.

  • 1

    It worked. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.