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
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):
You could then simplify your html to just like this:
would give you this output in HTML: