Jquery / javascript equivalent of CSS counter?

Is it possible to implement a counter that directly modifies the tag text using jQuery / Javascript? For example, if I had 2 tags:

<a>hello</a>
<a>bye</a>

After running the jQuery / JS function, this will happen:

<a>[1]hello</a>
<a>[2]bye</a>

I cannot use the CSS counter as I need a script to edit the HTML directly.

+4
source share
4 answers

you can use .html(function)

$("a").html(function(index, html) {
  return "[" + (index + 1) + "]" + html;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>
Run code
+5
source

You can skip all the bindings and add an index to the content with .prepend():

$("a").each(function(index,value) {
    $(this).prepend("["+(index++)+"] ");
})

Hope this helps.

$("a").each(function(index,value) {
   $(this).prepend("["+(index++)+"] ");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>
Run code
+1
source

,

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>

<script>
$("a").html(function(index, data) {
  return "[" + (index + 1) + "]" + data;
})
</script>
+1

With pure JS, you can create the text node and paste it as the first child node to get counters - see the demo below:

Array.prototype.forEach.call(document.querySelectorAll("a"), function(e, i) {
  e.insertBefore(document.createTextNode(`[${i+1}]`), e.childNodes[0]);
});
<a>hello</a>
<a>bye</a>
Run code
+1
source

Source: https://habr.com/ru/post/1665251/


All Articles