I'm setting the html of the body element in an iframe to a string str, then I want to access that content on the next line (here just using an alert call to display the content) but the html and append functions haven't completed by the time the alert statement is called.
$(function(){
....
$("#notes-tab span.add_draft").bind("click", function(e){
var str = '';
$(this).parent().siblings(".tab-content").children(".para").each(function(ind) {
str += $(this).find('div:first').html();
});
var curr = $("#content_rte").contents().find("body").html();
if (curr == ' ' || curr == '<br>') {
$("#content_rte").contents().find("body").html(str);
}
else {
$("#content_rte").contents().find("body").append(str);
}
alert($("#content_rte").contents().find("body").html());
});
});
And of course neither the html nor the append functions take callbacks.
Could someone tell me how one normally accomplishes waiting for the DOM to be changed before proceeding?
HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')
The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console. log("Hello"); setTimeout(() => { console.
Wait for function to finish using async/await keywords As you already know from the Promise explanation above, you need to chain the call to the function that returns a Promise using then/catch functions. The await keyword allows you to wait until the Promise object is resolved or rejected: await first(); second();
If you are using jQuery you can rely on .closest()
to figure out if the element you just created has a parent body
tag, and if it does it means it's been added to the DOM. You can write a function such as the following to allow you to actually do something when your element is ready:
callWhenReady: function (selector, callback, scope) {
var self = this;
if ($(selector).closest('body').length) {
callback.call(scope);
} else {
setTimeout(function () {
self.callWhenReady(selector, callback, scope);
}, 1);
}
}
html
and append
both call domManip
, which is a synchronous method, so alert
shouldn't even execute until those calls have completed.
Are you sure that the values you expect are being copied into the locations you expect?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With