How to write the following jQuery code in pure Javascript?

Asked

Viewed 54 times

1

I’m trying to convert the following code jQuery unsuccessful for javascript pure:

$.each($("p"), function(i, el) {
  var el = $(el);
  el.html(el.html() + " - " + i);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

<p>Teste</p>
<p>Teste</p>
<p>Teste</p>
<p>Teste</p>
<p>Teste</p>

What I’ve been able to do so far is:

var elements = document.querySelectorAll("p");

Array.prototype.forEach.call(elements, function(el, i){
    var el = el;
    var teste = el.innerHTML += 
    teste " - " + i;
});
  • By the way, even in Jquery, more idiomatic would be $("p").each(

1 answer

3


Variables need not be declared el and teste, only the section that concatenates the variable i in the el.innterHTML would be enough for the code to work, in fact they are not allowing the code to work properly:

Array.prototype.forEach.call(elements, function(el, i){
    el.innerHTML += " - " + i;
});

Using the Array prototype is also not necessary, since the variable elements is already eternal:

elements.forEach( (el, i) => {
  el.innerHTML += " - " + i;
});

The final code would be something like this:

document.querySelectorAll("p").forEach( (el, i) => {
  el.innerHTML += " - " + i;
});
<p>Teste</p>
<p>Teste</p>
<p>Teste</p>
<p>Teste</p>
<p>Teste</p>

Note that here, I didn’t even declare the variable elements, leaving another example of what can be done by effecting the forEach directly on the return of querySelectorAll.

  • 1

    Thanks for the reply, it worked very well, I have only doubt that I read about foreach being in disuse, that the best would be to use for.. in. That way you’d know what the most recommended form of code would look like?

  • There are some other ways, see this one: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for..of

Browser other questions tagged

You are not signed in. Login or sign up in order to post.