I’m trying to create an image slider and I need to be able to get the left or right margin of list items in my unordered list but I’m not able to get the needed margins using javascript. To try to achieve this I used document.querySelectorAll(“.item”)[0].style.marginLeft where .item is the class name given to each list item. While this doesn’t throw an error it gives an empty string.
The other problem I’m having is that although I gave each list item the same left margin value, the first list item has a left margin that is narrower than the rest of the list items. Please see my markup, styles, and script here.
The style property of an element only lists CSS properties defined in inline styles, or dynamically. That’s why it’s returning an empty string.
You’ll need to use the getComputedStyle method instead. This returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.
This will do what you want:
const el = document.querySelector(".item");
const styles = getComputedStyle(el);
console.log(styles.marginLeft)
That’s because you are using inline-block and the space between the tags in the html is accounted for just like the space between words. There are hacks to squash the space such as font-size:0 on the parent and then restate on the list items (not ems though as it would need to be rem or px). However these days you can use flexbox to better effect,