getComputedStyle not being updated when updating style for test

Viewed 763

I want to create a mock div that has display: none for testing purposes. However, setting the display in the test and then calling getComputedStyle shows no change in the style, i.e.

const parent = document.createElement('div');
const middle = document.createElement('div');

// If you check in the dom, the middle div clearly has display: none as 
// part of its style
middle.style.display = 'none';
parent.appendChild(middle);

// Supposed to be 'none', but is actually ''
console.log(getComputedStyle(middle).display);

It seems like other people have said that getComputedStyle forces a redraw of the screen, but it seems like it is not getting the updated display of middle. How can I force getComputedStyle to update to the display value?

2 Answers

getComputedStyle returns empty string for the display property unless the node is added to the DOM. You can see that also the initial computed style value is empty, because the node was not added to the DOM.

As mentioned in the spec, at step 5, the element has to be connected:

If elt is connected, part of the flat tree, and its shadow-including root has a browsing context which either doesn’t have a browsing context container, or whose browsing context container is being rendered, set decls to a list of all longhand properties that are supported CSS properties, in lexicographical order, with the value being the resolved value computed for obj using the style rules associated with doc.

const parent = document.createElement('div');
const middle = document.createElement('div');

console.log('Initial style: ', getComputedStyle(middle).display);
// If you check in the dom, the middle div clearly has display: none as 
// part of its style
middle.style.display = 'none';
parent.appendChild(middle);

// Adding this, now it shows the correct value
document.body.appendChild(parent);

// Supposed to be 'none', but is actually ''
console.log('Display: ', getComputedStyle(middle).display);

You need to add the parent element to the DOM using document.body.appendChild(parent). If an element is not in the DOM, it doesn't have any computed styles.

const parent = document.createElement('div');
const middle = document.createElement('div');

// If you check in the dom, the middle div clearly has display: none as 
// part of its style
middle.style.display = 'none';
parent.appendChild(middle);
document.body.appendChild(parent);

// Supposed to be 'none', but is actually ''
console.log(getComputedStyle(middle).display);

Related