简体   繁体   中英

Is a DOM element available immediately after it has been added to the DOM tree?

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.

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").

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM