Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  166] [ 1]  / answers: 1 / hits: 64503  / 11 Years ago, fri, april 19, 2013, 12:00:00

I am simply appending an element that is on the DOM like:



$(#div_element).append('<a href=#>test</a>');


Right after I append it I need access to the element I just made in order to bind an click function to it, I tried:



$(#div_element).append('<a href=#>test</a>').click(function(){alert(test)});


But the above didn't work. I could uniquely id the element but that seems like a bit to much work when perhaps there is a way I can get the element right after I append it.


More From » jquery

 Answers
59

You can do this:



var el = $('<a href=#>test</a>');

$(#div_element).append(el);

el.click(function(){alert(test)});

// or preferrably:
el.on('click', function(){alert(test)});


The append function accepts two types of arguments: a string or a jQuery element.
In case a string is passed in, it will create a jQuery element internally and append it to the parent element.



In this case, you want access to the jQuery element yourself, so you can attach the event handler. So instead of passing in the string and let jQuery create an element, you have to create the element first and then pass it to the append-function.



After you've done that, you still have access to the jQuery element to be able to attach the handler.


[#78775] Thursday, April 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamila

Total Points: 490
Total Questions: 94
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;