First I create element :
var link = document.createElement('a');
And my document is loaded, styles and scripts are in effect.
styles migt be for example:
a { background-color: salmon; }
so it applies to all A tags.
Does this newly created element in those circumstances has all CSS propertions set to their defaults as put in specification and is styled while inserted into DOM or is styled right at creation.
No, until the element's attached to the DOM it remains unstyled. Or, at least, its computed-style is unavailable (presumably because it's not yet rendered):
HTML:
<a href="#">Something</a>
CSS:
a {
color: purple;
}
JavaScript:
var body = document.getElementsByTagName('body')[0];
var a = document.createElement('a');
a.href = 'http://google.com/';
a.innerHTML = 'link to google';
console.log('color: ' + window.getComputedStyle(a,null).getPropertyValue('color'));
body.appendChild(a);
console.log('color: ' + window.getComputedStyle(a,null).getPropertyValue('color'));
JS Fiddle.
If, however, you explicitly style the element with JavaScript, which adds to the style attribute of the created element, that styling information is available immediately (albeit still not via the getComputedStyle()):
var body = document.getElementsByTagName('body')[0];
var a = document.createElement('a');
a.href = 'http://google.com/';
a.innerHTML = 'link to google';
a.style.color = 'green';
console.log('color: ' + a.style.color);
body.appendChild(a);
console.log('color: ' + a.style.color);
JS Fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With