Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Register an element in the DOM after setting html()

I have a div, where I set the innerHTML after a button has been clicked:

$('#headerDiv').html('Welcome [<a href=\'javascript:void(0);\' id=\'logout_button\'>Logout</a>]');

However, the new element logout_button isn't registered in the DOM, so I can't capture click events using the traditional $('#logout_button').click().

Is it possible to register logout_button in the DOM just after it's been set with the html() method?

Thanks!

like image 509
Brett Avatar asked Jun 06 '13 23:06

Brett


People also ask

How do you add an element to the DOM?

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

How can add DOM element in jQuery?

Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.

What jQuery function is used to insert markup into the DOM?

The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.


2 Answers

Delegate the event

$('#headerDiv').on('click', '#logout_button', function() {
     // Your code
});

This will make sure the event is attached to the dynamically added element by the concept of event bubbling.

like image 82
Sushanth -- Avatar answered Sep 23 '22 18:09

Sushanth --


If delegation isn't your cup of tea, you can bind your click handler to the button before attaching the button. Do that by creating DOM elements and appending them:

var btn = $('<a />').text('Logout').attr({
        "href": "javascript:void(0);",
        "id": "logout_button"
    }).click(function (e) {
        // do logout stuff
        e.preventDefault();
        return false;
    });
$('#headerDiv').append(btn);

This has the added bonus of ensuring you are adding valid elements to the DOM.

like image 42
pete Avatar answered Sep 20 '22 18:09

pete