Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/Javascript equivalent of CSS Counter?

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

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

After running the jQuery/JS function, this is what would happen:

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

I can't use a CSS counter as I need the script to directly edit the HTML.

like image 311
Russell C. Avatar asked Feb 05 '23 10:02

Russell C.


2 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>
like image 148
guest271314 Avatar answered Feb 08 '23 12:02

guest271314


You could loop through all the anchors and add the index to the content using .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>
like image 28
Zakaria Acharki Avatar answered Feb 08 '23 10:02

Zakaria Acharki