0

I have a div object with a property of width = 800. I want to assign the width of this div object to another div object.

<div id="object1" style="width: 800px;"></div>

<div id="object2"></div>

So as I'm coding on my javascript.js file, I tried to use the clientWidth method but didn't work.

var obj1 = document.getElementById("object1");
var obj2 = document.getElementById("object2");

obj2.style.width = obj1.clientWidth;

I've also tried using obj1.style.width but didn't work either. How do I change the properties of these objects by using another object's properties?

1
  • Change it to: obj2.style.width = obj1.clientWidth + 'px'; Commented Dec 2, 2016 at 22:17

4 Answers 4

3

obj1.clientWidth tells you the width in pixels but returns an integer. For the obj2.style.width you need to define if it's 'px', '%', 'em'. obj2.style.width expects a string like "1200px".

Change your code obj2.style.width = obj1.clientWidth + 'px'; to add the type of value to pixels.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to say 'px' of '%'. It has to be equivalent to the CSS string.

2 Comments

Thanks everyone! the +"px" worked like a charm! However, oddly enough, it only worked for clientWidth and not style.width
@Zulu: weird. What browser? I confirmed it in chrome in my console dynamically right on this site.
1

You have missed to specify the px, em or %

var obj1 = document.getElementById("object1");
var obj2 = document.getElementById("object2");

obj2.style.width = obj1.clientWidth+"px";
console.log(obj2.style.width)
<div id="object1" style="width: 800px;"></div>

<div id="object2"></div>

Comments

1

Use obj2.style.width = obj1.clientWidth+"px"; or obj2.style.width = obj1.style.width;. Both of them works fine for your case.

var obj1 = document.getElementById("object1");
var obj2 = document.getElementById("object2");

obj2.style.width = obj1.style.width;
//obj2.style.width = obj1.clientWidth+"px";
div{
  height:50px;
  background:red;
  display:inline-block;
  margin-bottom:10px;
  }
<div id="object1" style="width: 800px;"></div>

<div id="object2"></div>
So as I'm coding on my javascript.js file, I tried to use the clientWidth method but didn't work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.