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 3

brandonlind2
brandonlind2
7,823 Points

.attr() vs .hasClass

In this video he said .attr() would return the strings of all the classes if the element had multiple classes. I'm a bit confused couldn't you select something specific using the parameters in .attr()? Could someone please explain this a bit more in depth as to why .hasClass is better?

2 Answers

rydavim
rydavim
18,814 Points

I don't remember the specifics of the code for this project, so I will explain generally. If you're still not 100% comfortable with the reasoning, please post your code and we can walk through some different examples. :)

jQuery Documentation for attr()

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

In this case, you could use attr(attribute name, value) and then test whether that comes back true or false. However, using .hasClass already returns a Boolean.

jQuery Documentation for .hasClass

Determine whether any of the matched elements are assigned the given class. The .hasClass() method will return true if the class is assigned to an element, even if other classes also are.

Because .hasClass returns a Boolean, we don't need to do any additional expression testing. This means we have to do fewer steps to get what we're actually looking for, making our code more concise and easier to read.

That's not to say you can't use attr() to solve this problem, but I hope that helps clarify why .hasClass might be a better option in this case.

Well bro .attr() method can be used to get attributes a certain element has or we can set new attributes to that element .hasClass() method returns a boolean value considering weather the element really has that class or not if that particular element has that class...it would return true..if it doesnt..it will return false..

This is not what u want if u want the class to be returned as a string...attr() method will search if a particular attribute is there such as a class...and it will return tht class hope u understood please rate my answer