4

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.

2
  • For each one of the elements, set the text, then increment the number. Commented Dec 29, 2016 at 17:38
  • so select the elements, loop, and add the text?? Commented Dec 29, 2016 at 17:40

4 Answers 4

5

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

2 Comments

Why is .each() necessary? .html() iterates all elements of jQuery object.
This is another solution to the OP question :)
1

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>

Comments

1

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>

7 Comments

How is javascript at Answer different from javascript at stackoverflow.com/a/41384631?
@user7354735 no need for duplicate answers please.
This not a duplicate answer, I am just indicating the Place which is suitable to put the jQuery Function
Do not fight with me man, It is a simple and common script, can't write in a multiple way
And how changing html to data supposed to make difference?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.