1

Is it possible to change css properties within one line of code ? Here is what I do if I want to change two properties.

document.getElementById('el').style.display = "inline";
document.getElementById('el').style.backgroundColor = "#000000";
0

6 Answers 6

7

Move that styles to some class, and use class name instead of applying styles separately. This is recommended aproach.

/*CSS*/
.yourClass {
    display: inline;
    background-color: #000
}

//JS
document.getElementById('el').className = 'yourClass';

EDIT

Guys, please - stop writing jQuery examples. That is so simple task, that don't need at least 30KB library.

Sign up to request clarification or add additional context in comments.

2 Comments

He probably wants to change 'some style properties' of an element. In that case a complete class change is a bit too much.
You can always add a second class name instead of changing exsisting one. Using class instead of styles it's recommended practice, because it has better performance, and it's easier in implementation, especially, when you add additional properties. And, in class solution you don't have remember parameters before change, you only need to remove added class name from element.
2
document.getElementById('el').cssText = "display:inline; background-color:#000000";

2 Comments

Wouldn't this overwrite all other inline CSS?
yes but that would be the only way to do it in 1 line, without using any framework
2

you can try to change the class of the element using jqueryf for example :

$("p").addClass("myClass yourClass");

or use the attr method :

$("p").attr("class" yourClass");

Comments

0

You can do it liket his if you are using jQuery:

$("#el").css({ display : "inline", "backgroundColor" : "#000000" });

Comments

0

If you have the CSS values as string and there is no other CSS already set for the element (or you don't care about overwriting), make us of the cssText property:

document.getElementById("myElement").style.cssText = cssString;

Check SO link for more details https://stackoverflow.com/a/3968772/287100

Comments

0

Without any frameworks, there really isn't an acceptable solution. If you are wanting to prevent the repeated getElementById() calls, you could do something like this:

var el = document.getElementById('el').style;
el.display = "inline";
el.backgroundColor = "#000000";

or arguably more readable and semantically more correct:

var el = document.getElementById('el');
el.style.display = "inline";
el.style.backgroundColor = "#000000";

But that still doesn't solve the one-line problem. I highly recommend jQuery as the others have.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.