How to set IDs to elements with the condition of the first non-repeated character?

  • 0
    There are several titles with numbers in the first characters. Numbers can be repeated several times as the first characters in each new header. How to make the ID set only for those headers for which the number 1, 2, 3, etc. occurs for the first time? For example, so that from:

    <h2>1 сезон, 1 серия</h2>
    <h2>1 сезон, 2 серия</h2>
    <h2>2 сезон, 1 серия</h2>
    <h2>2 сезон, 2 серия</h2>


    It turned out:
    <h2 id="sezon-1">1 сезон, 1 серия</h2>
    <h2>1 сезон, 2 серия</h2>
    <h2 id="sezon-2">2 сезон, 1 серия</h2>
    <h2>2 сезон, 2 серия</h2>
    JavaScript Michael Morris, Jun 7, 2020

  • 3 Answers
  • 0
    var headlines = document.getElementsByTagName("h2");
    var arr = [];
    for (var i=0; i<headlines.length; i++) {
    var temp = headlines[i].innerText.split('')[0];
    if (!arr.includes(temp)) {
    headlines[i].setAttribute("id", "sezon-"+temp);
    arr.push(temp);
    }
    }
    Anonymous

  • 0
    Jaxon Arnold

  • 0
    document.querySelectorAll('h2').forEach(n => {
    const [ , season, episode ] = n.innerText.match(/(\d+)\D+(\d+)/);
    if (+episode === 1) {
    n.id = `season-${season}`;
    }
    });
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!