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
You’re on the right track, you can use the NodeList elements that you select with
[id^="msg"]
and pass them intoArray.from()
where you can use the second mapping argument to map each element to itsid
minus themsg
component (removed using.replace()
). Once you have an array of just your number components, you can spread this array intoMath.max()
to get the largest number from the array:An alternative is:
You can sort
Getting the element without extracting the ID
Getting just the largest number from the ID
Simply:
Explanation:
Math.max
, just like you predicted, the question is only what we will pass to it...
before the parameter converts an array to values, like at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/maxdocument.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...
converts the array-like-object returned bygetElementsByTagName
into an actual array, so we can call.map()
, a method available for arraysitem => 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 intMath.max