Home » Jquery » How can i add dynamic title to each li using jquery-Exceptionshub

How can i add dynamic title to each li using jquery-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:
    <ul>
    <li>test1</li>
    <li>test2</li>
    <li>test3</li>
    </ul>

There is a div for title like below:-

   <div class="title">
   <h1>ti</h1>
   </div>

I want to append title to to each li seprately and title is also coming in loop so when i am appending it getting the below Output which is not correct:-

    <ul>
    <li>
    test1 
    <div class="title">
     <h1>ti</h1>
    </div>
    <div class="title">
    <h1>ti</h1>
    </div>
    <div class="title">
    <h1>ti</h1>
    </div>
    </li>
    <li>test2<div class="title">
     <h1>ti</h1>
     </div>
     <div class="title">
    <h1>ti</h1>
     </div>
     <div class="title">
     <h1>ti</h1>
    </div></li>
    <li>test3<div class="title">
     <h1>ti</h1>
     </div>
     <div class="title">
     <h1>ti</h1>
    </div>
    <div class="title">
    <h1>ti</h1>
    </div></li>
    </ul>

While the expected output must be live below So please let me know how can i achieve the below output. Thanks a lot in advance. Response is need urgently:-

    <ul>
    <li>test1 
    <div class="title">
    <h1>ti</h1>
    </div>
    </li>
    <li>test2
    <div class="title">
    <h1>ti</h1>
    </div></li>
    <li>test3
    <div class="title">
     <h1>ti</h1>
    </div>
   </li>
    </ul>

Thanks again

How to&Answer:
$(function(){
  $('li').each((index, elem)=>{
     $(elem).append(`<h1>t${index}</h1>`);
  })
});