开发者

How do I make ordered list using javascript?

Lets sa开发者_StackOverflow社区y 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!


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;
  }
}


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


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


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;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜