sakeferret
sakeferret

Reputation: 315

jQuery access element after DOM loaded

I have loaded some content via innerHTML.

    $('#load-text-button').click(function () {
         document.getElementById("text-area").innerHTML="Some text <span class="footnote">The Footnote</span> Some other text.
    });

Now I want to access the newly created span (with a class of "footnote") when the "bold-footnote-button" is clicked. The footnote button was loaded on document load, but the text was loaded after the DOM loaded.

    $('#bold-footnote-button').click(function () {
        $(".footnote").addClass('bold');
    });

The ".footnote" element can't be found. Everything I've read points to using the .live method, but the docs say it's now deprecated. How do I access the new ".footnote" element without having to click on it directly?

Upvotes: 0

Views: 469

Answers (2)

wezzy
wezzy

Reputation: 5935

maybe i'm missing something but if you change your html on the first click() when you ask for $(".footnote") you should find the newly created span. Sometimes there are problem with the lag between DOM modification and DOM query but you have those problem only when you have your statements one after the other. In your case the browser has all the time to update itself while the user goes to #bold-footnote-button. Maybe the problem is that you use doublequote for the string and for the class attribute in your first example.

Check with your browser developement tools if it gets the class attribute correctly

Upvotes: 0

adeneo
adeneo

Reputation: 318182

The click function should work fine, as you're not targeting the newly inserted element with the event handler, but inside the event handler. The problem is probably that no such element was inserted as you have some issues with the quoting, do it like so:

$('#load-text-button').click(function () {
    $("#text-area").html('Some text <span class="footnote">The Footnote</span> Some other text.');
});

Upvotes: 1

Related Questions