Home > Software engineering >  Javascript - How to loop print html paragraph with id and class
Javascript - How to loop print html paragraph with id and class

Time:09-26

I want to print the paragraph element so that it includes the id number from 1 through 100. I want javascript to have to print them instead of writing them manually.

HTML code:

      <div id="shields">
       <p class="houses" id="1">HOUSE 1</p>
       <p class="houses" id="2">HOUSE 2</p>
       <p class="houses" id="3">HOUSE 3</p>
       <p class="houses" id="5">HOUSE 4</p>
       <p class="houses" id="6">HOUSE 5</p>
       <p class="houses" id="7">HOUSE 6</p>
       <p class="houses" id="4">HOUSE 7</p>
       <p class="houses" id="8">HOUSE 8</p>
       <p class="houses" id="9">HOUSE 9</p>
       <p class="houses" id="10">HOUSE 10</p>
      </div> 

Something like this where House 1 has the id number of 1. House print

CodePudding user response:

You can use javascript for loop to achieve this like the following

for (let i = 1; i <= 100; i  ) {
  let ptag = document.createElement('p');
  ptag.classList.add('houses');
  ptag.id = i;
  ptag.innerHTML = `HOUSE ${i}`;
  document.getElementById('shields').appendChild(ptag);
}
<div id="shields">
</div>

CodePudding user response:

You can use a for loop to loop from 1 to 100 and append the HTML dynamically to the div:

for (let i = 1; i < 101; i  ) {
  shields.innerHTML  = `<p class="houses" id="${i}">HOUSE ${i}</p>`;
}
<div id="shields"></div>

  • Related