Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Mobile Drop Down Menu Perform: Part 1

Gregor Šebela
Gregor Šebela
11,236 Points

Can attr() be used instead of val()?

In the code we have a line $option.val($anchor.attr("href")); which is assigning 'href' to a 'value' attribure.

Can this line be replaced with the line $option.attr("value", $anchor.attr("href"));

I get the same result. Therefore, I assume they are equal. Am I missing something?

1 Answer

Steven Parker
Steven Parker
229,732 Points

The val function is essentially a shorthand for attr("value", ... as you observed. Although it may be worth noting that API documentation describes it this way: "The .val() method is primarily used to get the values of form elements such as input, select and textarea." It also says "At present, using .val() on <textarea> elements strips carriage return characters from the browser-reported value." which is not mentioned in the documentation for attr. So that behavior might be different.

But I have also used it extensively as a shorthand with no issues so far.