cela
cela

Reputation: 2500

Cost/Benefits of using different ways to style HTML elements with JavaScript

I recently opened up one of my web projects in IntelliJ and noticed some hints/errors in my JavaScript that Netbeans was not showing.

The error was:

> Assigned expression type string is not assignable to type CSSStyleDeclaration

Here is the line it was showing on:

password.style = "border: 2px solid red";

While I have suppressed the hint by directly declaring what I am style, like so:

password.style.border = "2px solid red";

As someone mentioned in the comments, here is another way:

password.setAttribute("style", "border: 2px solid red";);

My question is what is the difference between the three? Are there any consequences/risks using the first way? Is there a best practice?

The first way works as far as I know across the browsers I have tested. Also, it seems odd that Netbeans would not show this as being an issue/hint.

Upvotes: 3

Views: 1137

Answers (1)

Fissure King
Fissure King

Reputation: 1270

According to mdn, HTMLElement.style should be treated as read-only and not used to set a style attribute string; instead it is a CSSStyleDeclaration, as IntelliJ has informed you.

If you're dead set on specifying style as a string, you can do so using, e.g., element.style.cssText = 'border: 2px solid red'.

EDIT: to further narrow the answer to your question, the consequence is that you no longer have access to the CSSStyleDeclaration object and as it is an unsupported means of setting style, you risk inconsistent results or broken code.

Upvotes: 4

Related Questions