gridContainer.width = width * CELL_LENGTH; // 1
gridContainer.style.width = width * CELL_LENGTH; // 2
gridContainer.style.width = width * CELL_LENGTH + "px"; // 3
I just figured out that the code in cases 1 and 2 are wrong. The problem is js doesn't complain about
either of them. No errors in console. Nothing!
How should I know or figure out things like this?? When there's no error and I don't know why it doesn't working other than trying different syntax until it works!
I used console and dev tools to figure it out as well but div.width seems to just adding another property to div that's useless for browser.
However for the second case, It just refuses to assign wrong syntax value to div.style.width without any complaint
This is true of other dynamic languages. For example, Python will also allow you to add arbitrary properties to objects without complaining.
As others have mentioned, you need to read MDN, and more specifically, understand the browser APIs and DOM structure. When you have an HTMLElement, you should know that you need to set style properties on
.style, and you should know that.styleis a CSSStyleProperties object which uses camelCased version of the CSS property names, and each property takes a certain type of value, like the various value types for the width property, which include length values, percentage values and keyword values.One of the main skills of being a frontend developer is learning this object model. It doesn't make sense to complain about it, because that is the job.
Trial and error is not an efficient way to learn. You should at the very least experiment in the browser with the dev tools open. Have a hypothesis for how something should work (like changing a particular property), try making the change and observe the effect on the webpage and in the dev tool inspector, and if your hypothesis is wrong, understand why and update your mental model. The goal is to avoid using trial and error eventually and build an understanding instead.