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 AJAX Basics (retiring) jQuery and AJAX Using jQuery's $.get() AJAX method

addClass() not working after load()

I've an empty div (id of menu) which is populated with a list of anchor tags through the $(selector).load('..") call. I am then trying to select first anchor tag and add a class to it -which does not work. However, when I execute the same in the browser console it does, why?

$('#menu a:first').addClass('active');

1 Answer

Steven Parker
Steven Parker
231,268 Points

The "load" method is asyncrhonous, and your code is probably running before the contents are available in the DOM. There's an optional callback argument you can use to do things that are dependent on the content after the load is complete. See the jQuery documentation page on .load() for more details.

Steven Parker Thank you! I used the success callback function for load() and moved the addClass() code there. Works perfectly!