简体   繁体   中英

Accessing Element property value in DOM using Javascript

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');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM