0

I have a loop to gather all elements of a certain class and insert something into that element.

var node;
var nodes = document.getElementsByClassName('myclass');
for(var i = 1; i <= nodes.length; ++i) {
  function () {
    var element = document.creatElement('script');
    node = document.getElementById('my-node' + i);
    node.parentNode.insertBefore(element, node);
  })();
}

I have some code that I need to make a callback to this because it uses the id of node but when I run that code it only runs on the last element of the array even if I call it in the for loop. Basically what I need is to keep the value of the node variable and use it in a callback function each pass through the loop.

If I understand javascript correctly, this means I need a callback, but I dont know how to write one for an immediately invoked function.

Nishi
  • 10,634
  • 3
  • 27
  • 36
BrandenB171
  • 294
  • 4
  • 20

1 Answers1

1

I did not understand exactly what you want, but if you want to keep the value you need to pass it to the function due the closure :

 var nodes = document.getElementsByClassName('myclass');
  for(i=1; i<=nodes.length; ++i){
    function(valueofI){
    var element = document.creatElement('script');
    node = document.getElementById('my-node'+valueofI);
    node.parentNode.insertBefore(element, node);
  })(i);
}

I hope it is what you need.

Jesse Teixeira
  • 131
  • 1
  • 4