0

I need to get the CSS style property from objects returned by the JavaScript querySelectorAll function, as follows:

elements = document.querySelectorAll(".login_window, .confirmation_message_window");

CSS style properties can be readily retrieved using the style parameter as shown below (the below is an example targeting just index 0):

elements[0].style

However this only returns style properties defined in-line, or style properties defined by setting them using the same method (which works because it puts them in-line).

Unfortunately, I need to retrieve the top style property which is defined in a CSS file.

Normally if there were only one instance of the class I would use jQuery for this via the .css() function, however I can't as I don't have the DOM object separated individually like I do using the method above as there are multiple instances of the same class.

It has been suggested this question is a duplicate of this question. As far as I can tell these answers do not provide a solution as they assume the user can provide a selector for the class, I am dealing with DOM objects provided through document.querySelectorAll for multiple instances of the same class.

A method similar to that suggested in the comments is to use:

style = window.getComputedStyle(elements[0]);
top = style.top;

This does work, except it returns the value in pixels, and annoyingly in the CSS in the file I have calc(50% - 120px); which is what I need, as I need to change just the 120px part to retain the calc component.

Community
  • 1
  • 1
Single Entity
  • 2,925
  • 3
  • 37
  • 66
  • If this is a duplicate, I would appreciate you explaining to me how I use those solutions for the elements object in my question. Because it doesn't answer my question as far as I can tell (I wish it did!) – Single Entity May 03 '17 at 11:49
  • You can use getComputedStyle(). var element = document.getElementById('image_1'), style = window.getComputedStyle(element), top = style.getPropertyValue('top'); – OhmnioX May 03 '17 at 11:49

0 Answers0