1

I am trying to extract the maximum value from each of the two submenus and append it to p.

$('.submenu').each(function(index, element) {
$('#output')
  .append($(".element").map(function() {
      return this.text();
    })
    .get().Math.max();
  );
 });
<div class='menu'>
  <div class='submenu'>
    <span class='element' style=''>1</span>
    <span class='element' style=''>5</span>
    <span class='element' style=''>7</span>
  <p id='output'>

  </p>

</div>
  <div class='submenu'>
    <span class='element' style=''>1</span>
    <span class='element' style=''>3</span>
    <span class='element' style=''>2</span>
  <p id='output'>

  </p>

  </div>
</div>

Thus, the output should look like:

<div class='menu'>
  <div class='submenu'>
    <span class='element' style=''>1</span>
    <span class='element' style=''>5</span>
    <span class='element' style=''>7</span>
  <p id='output'>7</p>

</div>
  <div class='submenu'>
    <span class='element' style=''>1</span>
    <span class='element' style=''>3</span>
    <span class='element' style=''>2</span>
  <p id='output'>3</p>

  </div>
</div>
Dambo
  • 3,318
  • 5
  • 30
  • 79
  • the use of multiple elements with the same ID attribute can cause problems you should change one of them – happymacarts Jan 23 '17 at 16:42
  • [`parseInt()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt) + [JavaScript: min & max Array values?](https://stackoverflow.com/questions/1669190/javascript-min-max-array-values) – Andreas Jan 23 '17 at 16:43

1 Answers1

1

There are several bugs in your code:

  1. Get .output within the current context by specifying the context as an argument.
  2. The text() is jQuery method so wrap this with jQuery.
  3. The usage of Math.max is not in a valid format in your code, use it with Function#apply to pass the array of elements as arguments.
  4. The id should be unique so use class instead for the output element and although specify the context in the selector.

$('.submenu').each(function(index, element) {
  $('.output', this).append(Math.max.apply(Math, $(".element", this).map(function() {
    return $(this).text();
  }).get()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='menu'>
  <div class='submenu'>
    <span class='element' style=''>1</span>
    <span class='element' style=''>5</span>
    <span class='element' style=''>7</span>
    <p class='output'>

    </p>

  </div>
  <div class='submenu'>
    <span class='element' style=''>1</span>
    <span class='element' style=''>3</span>
    <span class='element' style=''>2</span>
    <p class='output'>

    </p>

  </div>
</div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188