Add class to dynamically added element

1.2k views Asked by At

I have a shared left menu in a separate file from my pages so that I can update it in one place.

I am loading it onto the page in a .js file like so:

$(function () {
    $("#left-nav").load("templates/left-nav.html", function() {
        ...
    });

    ...
}

I would like to be able to set the nav-list item for the page to be selected. Something like this:

$("#calendar").addClass("selected");

...where #calendar is the ID of a list item in my left-nav.html template file.

Everything I've read says that I have to call addClass as a callback after I load in the file, but the following doesn't seem to work:

$(function () {
    $("#left-nav").load("templates/left-nav.html", function() {
        $("#calendar").addClass("selected");
    });

    ...
}

Question: Is it possible to add classes to dynamically added content on a page, and if so, how should I do it? Thanks!

1

There are 1 answers

0
Shriike On BEST ANSWER

The code is correct as written, adduming that left-nav.html does contain an element with the ID of calendar.

The completed event is fired after the HTML is added to the DOM according to the jQuery documentation.