[Vuejs]-How to know number of element in a DOM tree

2👍

You can use querySelectorAll() to get the elements, and use forEach() to display the elements along with their indexes (numbers):

var list = document.getElementById("myList");
var elements = Array.from(list.querySelectorAll("li"));

elements.forEach(function(li, index) {
  console.log(li.innerText + " is number " + (index + 1));
});

Demo:

var list = document.getElementById("myList");
var elements = Array.from(list.querySelectorAll("li"));

elements.forEach(function(li, index) {
  console.log(li.innerText + " is number " + (index + 1));
});
<ul id="myList">
  <li>Apple</li>
  <li>Orange</li>
  <li>Tomato</li>
  <li>Potato</li>
</ul>

3👍

No need any javascript code. v-for can handle what you want.

If you define your v-for like this: <li v-for="(fruit, index) in fruits">, index gives you the index number and you can print it out as {{ index + 1 }}

an example from the documentation website.

0👍

You can find the index of any element, please check the example.

var findIndex = "Tomato";
$("ul li").each(function(index, item) {
  if($(item).text() == findIndex){
    console.log("Index of " + findIndex + " is: " + (index + 1));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Apple</li>
  <li>Orange</li>
  <li>Tomato</li>
  <li>Potato</li>
</ul>

0👍

In case you’re trying to render the index in your v-for loop, you could use v-for="(item, index) of items" and then access {{index}}:

new Vue({
  el: '#app',
  data() {
    return {
      items: [ 'Apple', 'Orange', 'Tomato', 'Potato' ],
    }
  }
})
<script src="https://unpkg.com/vue@2.5.2"></script>

<div id="app">
  <ul>
    <li v-for="(item, index) of items">{{index}} - {{item}}</li>
  </ul>
</div>

See Vue’s Guide for List Rendering

👤tony19

Leave a comment