Search code examples
javascriptpositioningappendchildgetboundingclientrect

positioning new element based on position of existing element?


I am using the following code (Javascript within a webpage) to create a 'new' element in the DOM dynamically. I wish to position this say 200px 'below' an existing element. However my output has the positioning of the new element(s) all wrong...as if the position (top, left) I am specifying is ignored.

var _reference = document.getElementById("outputs");

for (_count = 0; _count < _limits; _count++) {

 var _structure = document.createElement("div"); 
 _structure.setAttribute("class", "container-fluid");
 _structure.setAttribute("id", "struct_" + _tally);
  if (_count === 0){
  _rect = _reference.getBoundingClientRect();  
    //get the bounding box of the "outputs" id element...
  document.getElementById("outputs").appendChild(_structure);   
  _structure.style.top = _rect.top + "200px";  //NOT positioned 200px below 'outputs'
  _structure.style.left = _rect.left;  //NOT positioned same position as 'outputs'
  }  //_count is "0"

}  //for loop

I would have thought this should be fairly straightforward...however it is driving me crazy...any help appreciated.


Solution

  • You'll need to set _structure.style.position to 'relative', 'absolute', 'fixed', or 'sticky' in order to use top, left, right, bottom.