-4

I was a beginner in JavaScript and jQuery.

here is my question

var a = $("selector").height(); // or other methods 

if I would like to change the height of this element to "b"

why should I write the $("selector").height("b"); instead of "a = b"??

4
  • Because height() is a function, and the same time, we can say it's a property when no value passed.
    – Adam Azad
    Jan 14, 2016 at 16:41
  • I was a beginner in JavaScript and jQuery - and then what happened?
    – Amit
    Jan 14, 2016 at 16:44
  • in most of jquery, something.foo() returns the current value(s) of whatever foo is, while something.foo(bar) sets the value of foo to bar.
    – Marc B
    Jan 14, 2016 at 16:44
  • @Amit Perhaps he took an -> to the knee Jan 14, 2016 at 16:44

4 Answers 4

5

That's the difference between setters and getters, as another programming language.

$(selector).height() returns the height of selector, so is a getter.

$(selector).height("90") sets a height of 90px, so is a setter.

When you make var a = $(selector).height() you are storing the height of the selector to the a variable.

1
  • Your answer made me understand the question, it seemed like utter non-sense to me before, thanks Jan 14, 2016 at 16:46
3

When you write var a = $("selector").height();, you are assigning the value of the height method call to the variable a.

You are not in any way creating a link to the actual height via the variable a. This is why you cannot say a=100 where 100 is the new height.

You must use the method call $("selector").height(a), where a is a variable containing the numerical value of the height you require.

1

Because b has to be attached to a jQuery object ($) in order to manipulate it in the DOM. making a = b simply equates the values. It does nothing to the DOM itself. You also need to remove the quotes from the "b" variable - otherwise you are passing the string "b" instead of the variable itself.

var b = 100;
$("selector").height(b); 
3
  • This is not valid code. var b=100px is not valid. EDIT: now it is after you have edited it.
    – psx
    Jan 14, 2016 at 16:47
  • you updated your answer, it was not valid before the edit.
    – psx
    Jan 14, 2016 at 16:48
  • 1
    I tried to ninja edit it after I realized I left the px on the 100. Thank you for catching it.
    – Korgrue
    Jan 14, 2016 at 16:50
1

The $.fn.height method without any arguments is a getter that will return a number. You can add or subtract that number to your hearts content but it wont get you anywhere.

When you pass an argument it becomes a setter that will actually change the selected element.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.