How do I make ordered list using javascript?

こ雲淡風輕ζ 提交于 2019-12-12 02:39:20

问题


Lets say I have this

<ol>
  <li>V1 One</li>
  <li>V1 Two</li>
  <li>V1 Three</li>
  <li>V1 Four</li>
</ol>`

I want to make an ordered list using .js instead of using LI tags. I was thinking the js. code could replace first V1 and call it 1. , replace second V1 and call it two and so on, in other words counting how many V1s there are and replacing them with ordered list.

Or maybe something like this

<ol>
  <li>i++ V1 One</li>
  <li>i++ V1 Two</li>
  <li>i++ V1 Three</li>
  <li>i++ V1 Four</li>
</ol>

Where i++ will be increased every time starting from 1

Yes, I know LI provide ordered list!


回答1:


Perhaps you want to loop through the children of <ol> and manipulate their innerHTML?

// Get the <ol> object from the DOM
var chillun = document.getElementById("yourOL").childNodes;

// Loop through the children of the <ol>
for(i=0;i<chillun.length;i++) {
  // Test that the node is indeed an <li>
  if(chillun[i].nodeName=='LI') {
    // Change this line to manipulate the text however you need
    chillun[i].innerHTML = i;
  }
}



回答2:


You can have an empty div, and use javascript to enter the innerHTML inside the div

function listdown(){
  var startlist = "<ol>";
  var endlist = "</ol>";
  *use a for loop to enter the <LI>, this way, you can do much more with each item*
  document.getElementById("emptydiv").innerHTML = startlist + LI list + endlist;
}

EDIT

Nonetheless, JQuery is still the best option




回答3:


I would advise you to learn(use) a javascript framework to accomplish this. It will speed up your javascript development rapidly. Jquery is very popular at the moment and I think you should also use that. Stackoverflow allready has a topic using Jquery describing what you want => Generating an unordered list with jQuery




回答4:


you could do something like this:

let ol = document.querySelector('ol');
let i = 1;
ol.querySelectorAll('li').forEach(function(li) {
    li.textContent = (i++) + ' ' + li.textContent;
});


来源:https://stackoverflow.com/questions/4731995/how-do-i-make-ordered-list-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!