skip to Main Content

I am a beginner with JavaScript and don’t know how to solve this simple issue.
I want to add text in h2 from an array with for loop

$(document).ready(function () {
  const titles = ["Title 1", "Title 2", "Title 3", "Title 3"];
  for (let i = 0; i < titles.length; i++) {
        var addText = "<h2>";
        addText += titles[i];
        addText += "</h2>";
    $(".ic-table-h2").append(addText);
  };
});
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<div class="container">
 <div class="ic-table-h2"></div>
 <div class="ic-table-h2"></div>
 <div class="ic-table-h2"></div>
 <div class="ic-table-h2"></div>
</div>

2

Answers


  1. $(document).ready(function () {
      const titles = ["Title 1", "Title 2", "Title 3", "Title 3"];
      for (let i = 0; i < titles.length; i++) {
            var addText = "<h2>";
            addText += titles[i];
            addText += "</h2>";
        document.querySelectorAll(".ic-table-h2")[i].append(addText);
      };
    });
    <script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
    <div class="container">
     <div class="ic-table-h2"></div>
     <div class="ic-table-h2"></div>
     <div class="ic-table-h2"></div>
     <div class="ic-table-h2"></div>
    </div>
    Login or Signup to reply.
  2. I am not really sure if I understood your problem correctly, but I would solve your problem like this (rebuilding the entire html inside your container, because this way you are flexible with your array size):

    $(document).ready(function () {
      const titles = ["Title 1", "Title 2", "Title 3", "Title 3"];
    
      var html = ''; 
      for (let i = 0; i < titles.length; i++) {
            html += "<div class='ic-table-h2'><h2>"+titles[i]+"</h2></div>"; 
      };
    
      $(".container").html(html); 
    
    });
    

    You could then simplify your html to just like this:

    <div class="container">
    </div>
    

    would give you this output in HTML:

    <div class="container"><div class="ic-table-h2"><h2>Title 1</h2></div><div class="ic-table-h2"><h2>Title 2</h2></div><div class="ic-table-h2"><h2>Title 3</h2></div><div class="ic-table-h2"><h2>Title 3</h2></div></div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search