0

I have a for loop, and I want that in my line, the left property of style, depends on my variable:

var pos = (i*100+100)px;

document.getElementsByName("ok")[i].style = 'position:absolute; left:pos';

Something like that.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
Rafo 554
  • 99
  • 5
  • i think you are looking for a javascript answer, so your html tag is wrong. – LongChalk Apr 26 '20 at 10:16
  • Does this answer your question? [Set CSS Left property of UL using Javascript](https://stackoverflow.com/questions/29664572/set-css-left-property-of-ul-using-javascript) – Rob Apr 26 '20 at 11:29

2 Answers2

1

You can something like this

var pos = (i*100+100);

const elem = document.getElementsByName("ok")[i];

elem.style.position = 'absolute';
elem.style.left = pos + 'px';
Kiran Shinde
  • 5,732
  • 4
  • 24
  • 41
  • A useful list of properties of the style object can be found here https://www.w3schools.com/jsref/dom_obj_style.asp – LongChalk Apr 26 '20 at 10:29
1

I think you are looking for something like

var DOM_elements = document.getElementsByName("ok");

for(var i=0; i < DOM_tags.length; i++) {
    var element = DOM_elements[i];
    var pos = (i*100+100);

    element.setAttribute('style','position:absolute; left:' + pos.toString());
}

This is risky though. You are in effect overwriting all other attributes of style (is that what you want?). Also worth noting - element.style is an object (not a string), so perhaps you would like element.style.position = 'absolute'; or something like that.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
LongChalk
  • 783
  • 8
  • 13