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
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
Share
Improve this question
asked Sep 15, 2018 at 15:00
karfkarskarfkars
4,0738 gold badges40 silver badges47 bronze badges
6
-
2
getComputedStyle(document.getElementById("id1")).getPropertyValue('background-color')
– dfsq Commented Sep 15, 2018 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 Commented Sep 15, 2018 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'); – karfkars Commented Sep 15, 2018 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! – karfkars Commented Sep 15, 2018 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 Commented Sep 15, 2018 at 15:30
3 Answers
Reset to default 4use window.getComputedStyle
read more https://developer.mozilla/en-US/docs/Web/API/Window/getComputedStyle
basically style
property only read the inline style on the element
You should try fetching the applied styles using the window.getComputedStyle method.
let element = document.getElementById("id1");
window.getComputedStyle(element);
Try getComputedStyle
window.getComputedStyle(document.getElementById("id1"));