Cannot apply style to dynamically created elements in javascript
I have the following code:
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
This code works as I expect it to, after appending the dynamic element to the document, a 5 x 5 blue box appears. The problem starts when I try to access the element via its className to style it further:
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';
This code should position the box but it does nothing, what am I doing wrong? Preferably I'm looking for a pure JS solution so no JQuery.
Thanks in advance :)
Problem
The default value of the property position of a div is static. When you try to set left/right [..] on static element it has no effect on that element.
static : every element has a static position by default, so the element will stick to the normal page flow. So if there is a left/right/top/bottom/z-index set then there will be no effect on that element. relative : an element's original position remains in the flow of the document, just like the static value.
Solution
- You have to set the position property in your created element to
absolute
,fixed
orrelative
.
let dynel = document.createElement('div');
dynel.className = 'foo';
dynel.style.position = "absolute"
dynel.style.width = '5px';
dynel.style.height = '5px';
dynel.style.backgroundColor = 'blue';
document.body.appendChild(dynel);
var foo = document.getElementsByClassName('foo');
foo[0].style.top = '50px';
foo[0].style.left = '200px';
top
, left
, right
, bottom
works on those elements in which position
property is not static
. But either absolute
or relative
or fixed
.
As per your requirement use any of the 3 values in your CSS and styles will start to apply. Something like this would work (But it depends how you want you implemention of the code)
var foo = document.getElementsByClassName('foo');
foo[0].style.position = "relative";
foo[0].style.top = '50px';
foo[0].style.left = '200px';
NOTE: position:fixed
and position:absolute
would get your element out of the normal code flow and you will have to adjust accordingly.
You need to ensure that foo[0]
has the position: absolute;
style set.