I have a page where some html is being dynamically added to the page.
This is the html and javascript that is created:
<div>
<script type="text/javascript" language="javascript">
$('#btn').click(function() {
alert("Hello");
});
</script>
<a id="btn">Button</a>
</div>
Looking in my Firebug console, I get an error that says:
TypeError: $(“#btn”) is null
jQuery is being loaded on the page initially.
What am I doing wrong here?
You have to bind
on()(or the events defined within theon()method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on$(document).ready()or similar.Bind to the closest element in which the
$('#btn')element will be appended that exists in the DOM on page-load/DOM ready.Assuming that you’re loading the
$('#btn')into the#containerdiv(for example), to give:Then use: