How to make a serial number for the neighbor below?

  • 0
    Good afternoon, I recently started learning js, there is a problem that needs to be solved, but I do not have enough experience and I did not find a solution to my problem that works for me, I tried to do it using nextElementSibling, alas nothing.
    The task itself: for the element #elem, find its neighbor below and add a serial number to it at the beginning.
    <ul>
    	<li>text</li>
    	<li>text</li>
    	<li id="elem">text</li>
    	<li>text</li>
    	<li>text</li>
    </ul>

    I tried it but it doesn't work for me.
    JavaScript Anonymous, Nov 13, 2019

  • 2 Answers
  • 0
    const elem = document.querySelector('#elem').nextElementSibling;
    if (elem) {
    const index = [...elem.parentNode.children].indexOf(elem);
    elem.innerText = (index + 1) + '. ' + elem.innerText;
    }
    Anonymous

  • 0
    document.querySelectorAll('ul > li').forEach((el, i)=>{
    if(el.id == 'elem'){
    el.nextElementSibling.prepend(i+2 + '. ');
    return false;
    }
    });
    Anonymous

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