Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is newly created element, that is not part of the DOM styled or has all values set to default?

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.

like image 705
rsk82 Avatar asked Jan 23 '26 12:01

rsk82


1 Answers

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.

like image 58
David Thomas Avatar answered Jan 26 '26 03:01

David Thomas