KYSSE
KYSSE

Reputation: 385

Make "Un-ordered list" behave like an "ordered list" with Javascript

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.

Upvotes: 1

Views: 255

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30370

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>

Upvotes: 1

Related Questions