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
203,258 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!