Reputation: 25607
After dynamically appending a chunk of HTML to a document (Example uses jQuery, but question is valid for all JavaScript), can I assume that the appended elements are available immediately afterwards?
$('#content').append('<p>Content</p><button id="newbutton">New</button><p>Some more content</p>');
var forExample = $('#newbutton').width(); // Element available?
In my particular case, creating single elements is not practicable. Also, this is long past the document.ready
event.
Upvotes: 3
Views: 225
Reputation: 1076
Yes, it's directly available. You could have tested it in 1min on fiddle... http://jsfiddle.net/adxbH/
var newButton = document.createElement('button');
newButton.id = 'newbutton';
newButton.innerHTML = 'button_test';
document.body.appendChild(newButton);
var forExample = document.getElementById('newbutton');
alert(forExample.offsetWidth);
As you can see, also very easy without using jQuery.
Upvotes: 0
Reputation: 382304
Yes, they're available immediately. jQuery will return you the correct objects, for example, and you may bind elements onto them.
But as they're not rendered while your script is running, size computations aren't always immediately made, so if you need the dimensions of the objects you might have to do
setTimeout(function(){
var forExample = $('#newbutton').width();
// use size
}, 0); // 0 is enough to tell the engine to render before it executes the callback
Note that the behavior of browser is different if you're incrementally debugging (the script isn't really "running").
Upvotes: 3