简体   繁体   中英

JavaScript use for loop to create p tag with innerHTML content filled in

i am using a for loop to generate paragraph tags based on the length of my array . I want each of these p tags generated to have the same innerHTML . I can get the tags to generate with the class name but the innerHTML remains blank .

I have tried the following to no avail, not sure what I am doing wrong.

for (i = 0; i < numArray.length; i++) { 

     var line = document.createElement("p");
     line.className = "line";
     document.body.appendChild(line);

     var b = document.getElementsByClassName("line");
     b.innerHTML = "|";


}

You don't need to call getElementsByClassName you can change the innerHTML of line since you already have the reference to the DOM element.

 for (i = 0; i < numArray.length; i++) { 

      var line = document.createElement("p");
      line.className = "line";
      line.innerHTML = "|"; 
      document.body.appendChild(line);

   }

And explaining why it didn't work, it's because getElementsByClassName returns a collecion of elements, you need to loop through them.

getElementsByClassName should return an array of elements, not a single element. You could try: getElementsByClassName('line')[i] , if there is some reason you are doing that specifically.

Note: getElementsByClassName('line')[i] may not refer to the object you just created, unless there are no other "line"s on the page. It scans the document for all elements that have a class called line, which could be paragraphs or other element types.


For a better alternative, please refer to changes made below. This:

  • caches the numArray length into a variable, so you are not performing that operation at each loop iteration
  • sets the HTML and ClassName of the element you created before attaching it to the document; which has a number of performance benefits
  • does not unnecessarily do a DOM lookup for elements, which is expensive
  • uses the var keyword to avoid scoping conflicts for loop variables

JS Fiddle :

for ( var i=0, n=numArray.length; i < n; i++) { 
  var line = document.createElement("p");
  line.className = "line";
  line.innerHTML = '|';
  document.body.appendChild(line);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM