Home > database >  JavaScript: Append text to h1 from an array with for loop
JavaScript: Append text to h1 from an array with for loop

Time:10-20

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 >
 <div ></div>
 <div ></div>
 <div ></div>
 <div ></div>
</div>

CodePudding user response:

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 >
</div>

would give you this output in HTML:

<div ><div ><h2>Title 1</h2></div><div ><h2>Title 2</h2></div><div ><h2>Title 3</h2></div><div ><h2>Title 3</h2></div></div>

CodePudding user response:

$(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 >
 <div ></div>
 <div ></div>
 <div ></div>
 <div ></div>
</div>

CodePudding user response:

Instead of trying to add the text inside the h2 you should append the h2 inside the container div.

For example:

   $(".container").append(addText);
  • Related