Click here to Skip to main content
15,923,142 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I was working on a package using the language JavaScript.
And I met up with a problem.
How can I link assign a varible?
Like this:
<pre lang="Javascript">
 var a = document.querySelector("div#foo").style.width;//$("div#foo")
 var b= 12;
 a=b;//want the value of 'a' to be 'b' not a itself.

What I have tried:

I have tried the above code but the logic doesn't work.
Graeme_Grant 23-Mar-24 20:13pm    
What does the browser Dev Tools console say?

1 solution

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'; = 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.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900