Home > Enterprise >  How would I iterate and retrieve the element with the highest innerText value using Javascript?
How would I iterate and retrieve the element with the highest innerText value using Javascript?

Time:08-30

How to get element with the highest value using javascript?

<div >1</div>
<div >0</div>
<div >4</div>
<div >0</div>
<div >2</div>

CodePudding user response:

Access all the elements that have a class of "score" by using document.getElementsByClassName it will return an array. Then iterate through the array and implement the logic that will get you the greatest value. You can use the below code

const elements = document.getElementsByClassName("score");
let greatestNumber = parseInt(elements[0].innerHTML)
let elementOfGreatestNumber = null
for(let index=1;index<elements.length;index  ) {
  const currentNumber = parseInt(elements[index].innerHTML)
  if(currentNumber > greatestNumber) {
    greatestNumber = currentNumber
    elementOfGreatestNumber = elements[index]
  }
}
console.log(elementOfGreatestNumber)

CodePudding user response:

Initialise a number variable to zero, and a selected variable to hold a div element.

Get all the div elements with querySelectorAll and iterate over them. Check to see if the the text content from the each div is greater than number. If it is set number to that value, and assign the div to selected.

After the iteration you have the element stored in selected. Here I'm adding a selected class to it.

const divs = document.querySelectorAll('div');

let number = 0;
let selected;

divs.forEach(div => {
  if (div.textContent > number) {
    number = div.textContent;
    selected = div;
  }
});

selected.classList.add('selected');
.selected { background-color: lightgreen; }
div { padding: 0.25em; 0.4em; width: 100px; }
<div >1</div>
<div >0</div>
<div >4</div>
<div >0</div>
<div >2</div>

CodePudding user response:

Method 1 - time complexity O(n log n)

first, sort the array in descending order. then get the first item.

b.innerText - a.innerText js will automatically convert string values to numbers.

const scores = Array.from(document.getElementsByClassName("score"))
const elm = scores.sort((a, b) => b.innerText - a.innerText)[0]

Method 2 - time complexity O(n)

as Devid mentioned, you can also do it using reduce method. this is a much more effective way to do it.

const scores = Array.from(document.getElementsByClassName("score"))
const elm = scores.reduce((a, b) => a.innerText - b.innerText > 0 ? a : b)

console.log(elm)
<div >1</div>
<div >0</div>
<div >4</div>
<div >0</div>
<div >2</div>

e.g.

const log = console.log;

log('3' - '1')
log('-3' - '1')

  • Related