0

I am trying to access the property of an element in my page. My ultimate goal is to switch a float property from left to right or vice versa if an onClick event happens. However, I am not having any luck even accessing an element.

I am trying to access the width property just to test and make sure my logic and code works. With the follwing code I get a 'null' return for myElement2 and I have also tried the myElement.style.getCSSPropertyVlaue function which my debugger says doesn't exist.

I am using Firefox debugger to test if this makes a difference.

var myElement = document.getElementById('leftPic');
var myElement2 = myElement.style.getPropertyValue('width');

console.log(myElement);
console.log(myElement2);
console.log('Test');
1
  • Can you provide your html? Commented Oct 31, 2013 at 22:02

1 Answer 1

1

You are using the incorrect code to get a CSS property's value with JavaScript. You want to use...

var myElement = document.getElementById('leftPic'),
var myElement2 = window.getComputedStyle(myElement).getPropertyValue('width');

Also, I'd choose a better variable name for storing the width in, as myElement2 is misleading.

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

1 Comment

Alex thank you, I am just learning Javascript and haven't heard any mention of the getComputedStyle function yet. I will do some research to understand it better. I agree with the function name, I was just looking to test some code and determine I am getting the output I would like. Again, thanks!

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.