1

I am trying to retrieve backgroundColor of an HTML Element. But when I check the style with js, everything is either empty or undefined. But when I check this element on developer console it I can see there is a backgroundColor. I could not understand what's wrong. Do you have any tips what can cause this problem?

document.getElementById("id1").style

JS get style result

Developer console

clockworks
  • 3,755
  • 5
  • 37
  • 46
  • 1
    `getComputedStyle(document.getElementById("id1")).getPropertyValue('background-color')` – dfsq Sep 15 '18 at 15:03
  • 2
    element `style` property only contains inline styles. `getComputedStyle` function gives you all the styles that are applied to the current element. – marzelin Sep 15 '18 at 15:04
  • Ok, I could get the style with JS. Actually I am trying to write unit test with react enzyme. How could I get the calculated style with react/enzyme. Following code does not work since style value is undefined! expect(wrapper.find('div.profile-card').props().backgroundColor).toBe('red'); – clockworks Sep 15 '18 at 15:09
  • By the way, could you see the attached images? I think imgur is not reachable from my country and I could not see the images? I am curious that is it visible to others? I would appreciate if you let me know! – clockworks Sep 15 '18 at 15:18
  • @wasabi yes it is visible. please edit your question and be more specific if the answers below do not address the issue – 95faf8e76605e973 Sep 15 '18 at 15:30
  • @95faf8e76605e973, thanks for the response. The answer addresses the issue, i will accept the solution. I think, Solving the problem for react should be a separate question! – clockworks Sep 15 '18 at 15:33

3 Answers3

4

use window.getComputedStyle

read more https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

basically style property only read the inline style on the element

ashish singh
  • 6,526
  • 2
  • 15
  • 35
1

You should try fetching the applied styles using the window.getComputedStyle method.

let element = document.getElementById("id1");
window.getComputedStyle(element);
95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
Vikram Patil
  • 152
  • 2
  • 11
  • I try this code but it did not work on chrome javascript console! Can you confirm that there is no syntax error at the code? – clockworks Sep 15 '18 at 15:11
0

Try getComputedStyle

window.getComputedStyle(document.getElementById("id1"));
brk
  • 48,835
  • 10
  • 56
  • 78