Russell C.
Russell C.

Reputation: 608

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.

Upvotes: 4

Views: 932

Answers (4)

user7354735
user7354735

Reputation: 83

Use this code,

<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>

Upvotes: 1

kukkuz
kukkuz

Reputation: 42370

With pure JS, you can use create a text node and insert it as the first child node to get the counters - see a 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>

Upvotes: 1

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

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>

Upvotes: 1

guest271314
guest271314

Reputation: 1

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>

Upvotes: 5

Related Questions