HotDrink HotDrink - 7 months ago 11
HTML Question

Looping through a set of <p>'s one at a time

I'm trying to figure out how to count the number of p's so every time the button is pressed, it outputs to 0 to 1 until the maximum number of p's is counted.

var big_number = 999999;
var i;
var a = document.getElementsByTagName("p");
function function0() {
for (i=0; i < big_number; i++) {
document.getElementsByTagName("p")[i].innerHTML="text";
}
}


I want it to write to another p every time the button is pressed.

Answer

Make a generic tag adder function then call it:

function addTags(tagName,start, max, container) {
  var i = start;
  for (i; i < max; i++) {
    var newp = document.createElement(tagName);
    newp.innerHTML = "paragraph" + i;
    container.appendChild(newp);
  }
}
var tag = 'p';
var big_number = 30;
var i;
var a = document.getElementsByTagName(tag );
// **THIS is your specific question answer**:
var pCount = a.length;
var parent = document.getElementById('mydiv');
addTags(tag,pCount , big_number, parent);
// add 10 more
a = document.getElementsByTagName(tag );
pCount = a.length;
big_number = big_number+10;
addTags(tag,pCount , big_number, parent);
Comments