List all IDs starting with a specified string followed by a number, remove the string, and get the biggest number value

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)

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>

4

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>

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>

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật