Cannot insert correctly when trying to achieve CSScounter effect with js

when I was watching the css tutorial today, I saw the css counter and wondered if I could implement it with js

<body>
    <div>
    

q

w

e

r

a

</div> <script> var list = document.getElementsByTagName("p"); // queryselectorallnodelist var para = document.createElement("p"); var into; var text; for(var i = 0;i<list.length-1;iPP){ into = "Para "; into += i+1; into += " "; text = document.createTextNode(into); para.appendChild(text); console.log(into); console.log(text); list[i].parentNode.insertBefore(para,list[i]); } </script> </body>

the result is as follows:

I understand because only one P is created outside the for, and then I changed it

.
var par;
        var text;
        for(var i = 0;i<list.length;iPP){
            var into = "Para ";
            into += i+1;
            into += " ";
            par = document.createElement("p");
            text = document.createTextNode(into);
            par.appendChild(text);
            console.log(into);
            console.log(text);
            list[i].parentNode.insertBefore(par,list[i]);

I think this should work, but the result is that the interface cannot be loaded. Google and IE are both.

Wow! kneel for an answer!

Jun.09,2022

correct js

    var list = document.getElementsByTagName("p");
    for (var i = 0, len = list.length; i < len; iPP) {
      var para = document.createElement("p");
      var into = "Para " + (i + 1) + ' ';
      var text = document.createTextNode(into);
      para.appendChild(text); 
      list[i].parentNode.insertBefore(para, list[i * 2]);
      para = null;
    }
    The end condition list.length of the
  1. for loop is variable. You add new nodes to the list in the loop, so list.length is getting bigger, so after your updated code, the loop won't stop. Your browser explodes
  2. The usage of
  3. insertBefore. In the code before you update, insert normally during the first loop. In the following loop, para in the child nodes of list [I] .parentNode , all subsequent operations are in the order of changing nodes
  4. .

solve:

  1. use variables to save list initial length as for loop end condition
  2. reassign values to para each time in the for loop to avoid updating the node order
  3. the length of list changes after the new node is inserted, so use iNode 2 to indicate the node to be inserted (Q, w, e..)
Menu