How do I create an HTML element and set its style attributes in javascript [closed]

2 weeks ago 18
ARTICLE AD BOX

Various documentation seems to indicate that I can do:

const e = document.createElement('div'); e.style.left = '100px'; e.style.top = '100px';

and, indeed, if I type this into a browser console, one line at a time, it works. However, if I place this code in a function, and run the function from the browser console, I get an error saying e.style is undefined. Adding the line

e.style = '';

right after the createElement has no effect. I've tried this in Chrome and Firefox.

What does work (both individually and in a function) is:

const e = document.createElement('div'); e.style = 'left:100px;top:100px;';

Why?

EDIT: The above code actually works fine; I oversimplified it. Here's a short HTML file that demonstrates the problem. Ostensibly the constructors Box and Nox do the same thing. But new Box() works, while new Nox() doesn't. Maybe it's something stupid. But I don't see it...

<!DOCTYPE HTML> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <script> const boxes=[]; function Box(x,y,txt) { const e = this.element = document.createElement('div'); e.className='box' e.style = 'left:'+(this.x = (x || 0))+'px;top:'+(this.y = (y || 0))+'px;'; e.innerHTML = '<p>'+txt+'</p>'; document.body.appendChild(e); boxes.push(this); } function Nox(x,y,txt) { const e = this.element = document.createElement('div'); e.className='box' e.stlye.left = (this.x = (x || 0))+'px'; // x position of upper left e.style.top = (this.y = (y || 0))+'px'; // y position of upper left e.innerHTML = '<p>'+txt+'</p>'; document.body.appendChild(e); boxes.push(this); } </script> <style> div.box { position:absolute; top:0; left:0; height:30px; border:1px solid black; display:flex; align-items:center; justify-content:center; } </style> </head> <body> </body> </html>
Read Entire Article