Ad

Trying To Do Some Jquery Code After Append

- 1 answer

I have some links and I want something to happen when I click on the link. However, I’m creating these elements with .append This is my jQuery code :

$(".ClickTools").click(function(){alert(1);});

It doesn’t work after the .append, but it does work when the element is there already (without using append). I need this code to work even when the element has been added to the page with append

This is html code:

<div id="appender"></div>

And this is my jQuery append code:

$("#appender).append('<a class=".ClickTools">click on me</a>');

When I click on the Click on me button, nothing happens. Can anyone explain why?

Ad

Answer

as the dom-element is not existent on parsing, you have to bind event to an element that´s already there, e.g document:

$(document).on('click', '.ClickTools',function(){ console.log(123) });

Also you dont need the dot (.) while appending and setting classname (fixed also the missing quote )

$("#appender").append('<a class="ClickTools">click on me</a>');
Ad
source: stackoverflow.com
Ad