ruit
ruit

Reputation: 15

What is the difference between element.style="height: 90px;" and element.style.height="90px";?

Are there any differences between these 2 lines?

document.querySelector("div").style="height: 90px;"
document.querySelector("div").style.height="90px";

Upvotes: 0

Views: 328

Answers (2)

CertainPerformance
CertainPerformance

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 in elt.style = "color: blue;"), since it is considered read-only, as the style attribute returns a CSSStyleDeclaration object which is also read-only. Instead, styles can be set by assigning values to the properties of style. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in elt.style.color = '...') as using elt.style.cssText = '...' or elt.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 using elt.style.<property> (i.e., elt.style.fontSize, not elt.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

jeffjenx
jeffjenx

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

Related Questions