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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With