2

This is probably too basic but I'm unable to figure out how this is done.

To modify one CSS property of a div, I do this:

$('#myDiv').css('width', '300');

What if I want to modify both width and height?

This --

$('#myDiv').css('width', '300', 'height', '250');

-- didn't work.

Chaining it works:

$('#myDiv').css('width', '300').css('height', '250');

-- but I'm wondering if there's more elegant, simpler syntax for it. Would be grateful for someone's advice.

1 Answer 1

5

Try this

$('#myDiv').css({width: '300', height: '250'});

From official documentation

jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css({'background-color': '#ffe', 'border-left': '5px solid #ccc'}) and .css({backgroundColor: '#ffe', borderLeft: '5px solid #ccc'}). Notice that with the DOM notation, quotation marks around the property names are optional, but with CSS notation they're required due to the hyphen in the name.

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

3 Comments

Thank you, Claudio. Tried it. Didn't work. Are there any other ways?
should be $('#myDiv').css({width: '300', height: '250'});. Notice the : instead of the ,
Great! Thanks Claudio, Thanks Hunter!

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.