Reputation: 15
Are there any differences between these 2 lines?
document.querySelector("div").style="height: 90px;"
document.querySelector("div").style.height="90px";
Upvotes: 0
Views: 328
Reputation: 370879
One difference is that when you assign to the .style
property, you will overwrite whatever used to be assigned to the .style
property, if anything:
// this next assignment will be immediately overwritten!
document.querySelector("div").style = 'background-color: yellow';
document.querySelector("div").style = "height: 90px;"
div {
background-color: green;
}
<div>
x
</div>
// Not overwritten anymore!
document.querySelector("div").style.backgroundColor = 'yellow';
document.querySelector("div").style.height = "90px";
div {
background-color: green;
}
<div>
x
</div>
Another problem is that the style
object is supposed to be read-only, although popular web browsers allow it. See MDN:
Styles should not be set by assigning a string directly to the
style
property (as inelt.style = "color: blue;"
), since it is considered read-only, as the style attribute returns aCSSStyleDeclaration
object which is also read-only. Instead, styles can be set by assigning values to the properties ofstyle
. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties ofstyle
(as inelt.style.color = '...'
) as usingelt.style.cssText = '...'
orelt.setAttribute('style', '...')
sets the complete inline style for the element by overriding the existing inline styles. Note that the property names are in camel-case and not kebab-case while setting the style usingelt.style.<property>
(i.e.,elt.style.fontSize
, notelt.style.font-size
).
Assigning to it isn't a good idea. For better compatibility, assign to the .style.cssText
(or only assign to a particular property, like .height
):
document.querySelector("div").style.cssText = "height: 90px;"
div {
background-color: green;
}
<div>
x
</div>
Upvotes: 2
Reputation: 17467
document.querySelector("div").style="height: 90px;"
will override the entire style
attribute of the selected div element, erasing any other properties that may have been set via the style attribute.
document.querySelector("div").style.height="90px";
will only update the height
property.
Upvotes: 1