Reputation: 81
I am loading remote HTML into a DIV using jQuery and need to access all the elements and JS contained therein. Seems as though the inserted HTML is added and renders correctly but the elements are not in the DOM. How can I access these new elements ? Using document.getElementById('myDiv') returns null
var canvas .. in the script below returns null and I don't understand why.
<script>
function draw(){
var canvas=document.getElementById("pdf1");
var pdf=canvas.getContext("2d");
// other code here populates canvas.....
}
</script>
<body>
<div>
<canvas id="pdf1" width="801" height="1041"></canvas>
</div>
</body>
<script type="application/javascript">
$(window).load(draw());
</script>
</html>
Upvotes: 0
Views: 1143
Reputation: 22241
$('#new_html_wrapper').load('file.html', function(){
// Access the new DOM elements here inside the load callback.
$(this).on('#myDiv','click',function(){
alert('You clicked on myDiv!');
});
$('#myDiv', this).css('background','red');
});
// Accessing the elements here will fail as they haven't been loaded yet.
Read more: http://api.jquery.com/load/
Also don't use document.getElementById('myDiv')
.
You already have jQuery loaded so do: $('#myDiv')
.
Upvotes: 1
Reputation: 5974
You would have tried to get the content before HTML inserted there.
you should try accessing the element after content inserted. i.e. if you call the same function after content inserted, you can get the content in div.
or if you want to bind some events like click, on the content which comes later(inserted data like in your case) as well, you can live bind the events as below
$("div.className").live("click",function(){ alert('1'); })
or
$("document").on("div.className","click",function(){ alert('1'); })
Upvotes: 0
Reputation: 7576
If you need to bind events to those new elements use the .on() function
Upvotes: 0