skip to Main Content

A page contains dozens of elements with IDs that look like: <a id="msg{number}"></a> The IDs are unique and are in no particular order, for example:

<a id="msg988755"></a>
<a id="msg129"></a>
<a id="msg7756501"></a>
<a id="msg745"></a>
<a id="msg657550"></a>
<a id="msg1148"></a>
<a id="msg87905541"></a>
<a id="msg745102"></a>
<a id="msg31780"></a>
<a id="msg2657588"></a>
<a id="msg8895"></a>

My goal is to use pure JS find the ID with the biggest number (after removing the ‘msg’ part from the ID), meaning that the result of the script should be this number: 87905541

I think the script should run a query to find all IDs that start with ‘msg’, eg. document.querySelectorAll('[id^="msg"]')]; but from there I’m stuck. I read that this function could find the biggest number: Math.max(num)

4

Answers


  1. You’re on the right track, you can use the NodeList elements that you select with [id^="msg"] and pass them into Array.from() where you can use the second mapping argument to map each element to its id minus the msg component (removed using .replace()). Once you have an array of just your number components, you can spread this array into Math.max() to get the largest number from the array:

    const max = Math.max(...Array.from(
      document.querySelectorAll('[id^="msg"]'), 
      ({id}) => id.replace("msg", "")
    ));
    
    console.log(max);
    <a id="msg988755"></a>
    <a id="msg129"></a>
    <a id="msg7756501"></a>
    <a id="msg745"></a>
    <a id="msg657550"></a>
    <a id="msg1148"></a>
    <a id="msg87905541"></a>
    <a id="msg745102"></a>
    <a id="msg31780"></a>
    <a id="msg2657588"></a>
    <a id="msg8895"></a>
    Login or Signup to reply.
  2. An alternative is:

    <html lang="en">
      <body>
        <a id="msg988755"></a>
        <a id="msg129"></a>
        <a id="msg7756501"></a>
        <a id="msg745"></a>
        <a id="msg657550"></a>
        <a id="msg1148"></a>
        <a id="msg87905541"></a>
        <a id="msg745102"></a>
        <a id="msg31780"></a>
        <a id="msg2657588"></a>
        <a id="msg8895"></a>
      </body>
    
      <script>
        const arrID=[];
        const collID= document.querySelectorAll('[id^=msg]');
    
        for (var i = 0; i < collID.length; i++) {
            var temp= collID[i].id;
            arrID.push(temp.replace('msg',''));      
        }
        
        console.log(Math.max(...arrID));
      </script>
    Login or Signup to reply.
  3. You can sort

    Getting the element without extracting the ID

    window.addEventListener('load', () => { // after the page loads and the elements are present
      const largest = Array.from(document.querySelectorAll('a[id^=msg]'))
        .sort((a, b) => a.id.localeCompare(b.id, 'en', { numeric: true })) // the compare needs to take the numbers into account
        .pop();
      largest.classList.add('largest');
    });
    .largest {
      text-decoration: underline;
    }
    <pre>
    <a id="msg988755">msg988755</a>
    <a id="msg129">msg129</a>
    <a id="msg7756501">msg7756501</a>
    <a id="msg745">msg745</a>
    <a id="msg657550">msg657550</a>
    <a id="msg1148">msg1148</a>
    <a id="msg87905541">msg87905541</a>
    <a id="msg745102">msg745102</a>
    <a id="msg31780">msg31780</a>
    <a id="msg2657588">msg2657588</a>
    <a id="msg8895">msg8895</a>
    </pre>

    Getting just the largest number from the ID

    window.addEventListener('load', () => { // after the page loads and the elements are present
      const largest = Array.from(document.querySelectorAll('a[id^=msg]'))
        .map(anchor => anchor.id)
        .sort((a, b) => a.localeCompare(b, 'en', { numeric: true })); // the compare needs to take the numbers into account
      console.log(largest.pop().replace('msg',''));
    });
    <a id="msg988755"></a>
    <a id="msg129"></a>
    <a id="msg7756501"></a>
    <a id="msg745"></a>
    <a id="msg657550"></a>
    <a id="msg1148"></a>
    <a id="msg87905541"></a>
    <a id="msg745102"></a>
    <a id="msg31780"></a>
    <a id="msg2657588"></a>
    <a id="msg8895"></a>
    Login or Signup to reply.
  4. Simply:

    console.log(Math.max(...[...document.getElementsByTagName("a")].map(item => parseInt(item.id.substring("msg".length)))))
    <a id="msg988755"></a>
    <a id="msg129"></a>
    <a id="msg7756501"></a>
    <a id="msg745"></a>
    <a id="msg657550"></a>
    <a id="msg1148"></a>
    <a id="msg87905541"></a>
    <a id="msg745102"></a>
    <a id="msg31780"></a>
    <a id="msg2657588"></a>
    <a id="msg8895"></a>

    Explanation:

    • we will call Math.max, just like you predicted, the question is only what we will pass to it
    • the ... before the parameter converts an array to values, like at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
    • document.getElementsByTagName("a") gets the anchors, of course, you might need some other selector in your real code if you have some anchors that you want to select and you want to avoid selecting some others, but here I selected them by the tag name due to not having any other specification
    • the ... converts the array-like-object returned by getElementsByTagName into an actual array, so we can call .map(), a method available for arrays
    • item => parseInt(item.id.substring("msg".length)) is an arrow function passed to .map() which will run for all items in the array and for each, it will get the value after msg, convert it to int
    • so the result is an array of integers which represent the numeric value of each ids as specified in the question and we destructure this array into parameters to be passed to Math.max
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search