1. You should not use
var[
^] normally, you should be using
let[
^] or
const[
^] instead.
2. For selecting elements by id, it is better to use
getElementById()[
^].
3. looking at the element
style
for the
width
will only return a width
if you set the style, it will not return the actual width. For that you need to use a function -
getBoundingClientRect()[
^]
4. The
width[
^] property is a
length[
^]. Lengths require units to give a value meaning. using var
b = 12;
is an invalid length. See the
length[
^] for all of the valid units.
So, your final code should be:
const a = document.getElementById('foo');
const b = '12rem';
a.style.width = b;
Learn to use the tools available to you to debug your code. Debugging is an invaluable skill for writing code and fixing bugs. See this:
Debug JavaScript | DevTools | Chrome for Developers[
^] and this:
The Firefox JavaScript Debugger — Firefox Source Docs documentation[
^]
You need to take the time and learn the basics of the language. Mosh is a great trainer. Here is his YouTube series on Javascript:
What is JavaScript? - YouTube[
^].
Also, you need a good reference. Here is what I use:
MDN Web Docs[
^].
Lastly, learn to use
Google Search[
^]. It is a key research tool for programmers.