1

I need to display numbers which each list item in an un-ordered list. To achieve this, I tried to convert an un-ordered ul list tag into an ordered ol list tag (see my script below). I need to do this because I want each li tag to display its order number next to it.

Here is the script that I tried which I found on codepen:

var ul = document.getElementsByClassName("productGrid")[0]
var ol = document.createElement("ol");

var li = ul.querySelectorAll('li');
for(var i=0;i<li.length;i++) {
  ol.appendChild(li[i]);
}

setTimeout(function() {
  ul.parentNode.replaceChild(ol,ul);
},1000);

This works but as expected it ruined the "styles" set to that ul tag. So instead of turning it into an actual ol tag, I need to keep it as a ul and display numbers some other way.

How can I use JavaScript to find out how many li's are inside the ul tag and then display the appropriate number within the li tag (via something like a span tag)

Any help with this would be much appreciated.

4
  • 1
    ol1 is not a tag name I've ever heard of? Did you mean ol? If ol, that will select an existing ordered list, not an existing unordered list Commented Feb 6, 2019 at 1:01
  • “I need to do this because I want each li tag to display its order number next to it.” You mean like what happens when you apply the CSS list-style: decimal? Commented Feb 6, 2019 at 1:03
  • I just pasted in the wrong snippet. i fixed it.. Commented Feb 6, 2019 at 1:04
  • list-style: decimal could work but how do i style the number? Commented Feb 6, 2019 at 1:06

1 Answer 1

1

Have you considered a pure-CSS based approach instead?

You could achieve a similar counting effect on an unordered-list without the need for JavaScript via the :before pseudo-element, and the counter-reset and counter-increment CSS properties.

Here's a snippet to demonstrate this technique in action:

.number-list {
  /* Init your custom counter for children */
  counter-reset: number-list-counter;

  /* Hide point list style */
  list-style:none; 
}

.number-list li {
  position:relative;
}

.number-list li:before {
	/* 
  Set content of pseduo element by parent counter
  and increment the counter 
  */
  content: counter(number-list-counter);
  counter-increment: number-list-counter;
  
  /* Offset position of counter pseduo elements */
  position:absolute;
  top:0;
  left:-2rem;

  /* Apply some styling to the numbering */
  color: red;
  font-weight:bold;
  font-size:1.5rem;
}
<ul class="number-list">
  <li>Apple</li>
  <li>Orange</li>
  <li>Banana</li>
<ul>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.