Search code examples
jquerymeta-tags

Get the higher number in a group of meta tag names


I have a group of meta tags with a consistent name (session-1/2/3/4...etc). The group will be different every time depending on how many meta the user needed.

I am trying to get the higher number in that meta group and grab the content. In this example, will be grabbing "session-3" content.

Not too sure how to start.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<meta name="session-1" content="frist">
<meta name="session-2" content="second">
<meta name="session-3" content="third">

Solution

  • In plain js is simple enough.

    let resultElement, count = 0
    document.querySelectorAll('meta').forEach(el => {
      // for each meta element
      let met = el.name.split('-')
      // split name into number and seassion
      if (met[0] === 'session' && parseInt(met[1]) > count) {
        count = parseInt(met[1]), resultElement = el
      }
      //if there is seassion in name and if number is bigger then previues save it in count and save result element
    })
    
    console.log(resultElement.content)
    <meta name="session-1" content="frist">
    <meta name="session-2" content="second">
    <meta name="session-3" content="third">