Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,135 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.