Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript: Use reduce() method to determine widest DOM element?

I’m trying to use the Javascript reduce() method to find the element with the largest width in a set of DOM nodes:

function get_elementWidth(ELEMENT) {
  const DOMrect = ELEMENT.getBoundingClientRect();
  const width = DOMrect.width;
  return width
}

function get_widestElemet(ELEMENTS) {
  const widestElement = ELEMENTS.reduce((a, b) => Math.max(get_elementWidth(a), get_elementWidth(b)))
  return widestElement;
}

const elements = document.querySelectorAll('.ElementGroup__element');
console.log(get_widestElemet([...elements]))
.ElementGroup {
  display: flex;
  flex-direction: column;
}
<div class="ElementGroup">
  <span class="ElementGroup__element">Short Element</span>
  <span class="ElementGroup__element">Short Element</span>
  <span class="ElementGroup__element">Looooooooooong Element</span>
</div>

However, this approach throws the error ELEMENT.getBoundingClientRect is not a function (run the snippet + check the console). I believe this happens because the final value passed to my get_elementWidth(ELEMENT) function (by the reduce() method) is the actual largest width (so a number and not a DOM node), but I don’t know how to solve it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need to use reduce here, just map get_elementWidth to each ELEMENT and then take Math.max of all the values:

function get_elementWidth(ELEMENT) {
  const DOMrect = ELEMENT.getBoundingClientRect();
  return DOMrect.width;
}

function get_widestElement(ELEMENTS) {
  const widestElement = Math.max(...ELEMENTS.map(get_elementWidth))
  return widestElement;
}

const elements = document.querySelectorAll('.ElementGroup__element');
console.log(get_widestElement([...elements]))
.ElementGroup {
  display: flex;
  flex-direction: column;
}
<div class="ElementGroup">
  <span class="ElementGroup__element">Short Element</span>
  <span class="ElementGroup__element">Short Element</span>
  <span class="ElementGroup__element">Looooooooooong Element</span>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading