简体   繁体   中英

jQuery .prepend to non-existent element - is it a JS bug?

I want to prepend a form to an element on a page right after the parent element is added to DOM. When I prepend too early, ie the parent element doesn not exist yet I get a strange beheavor.

jQuery(".myDiv").prepend('<div id="myForm">Content</div>');

If I check the existance of the prepent element right after with jQuery or even with JS like this:

var res = document.getElementById("myForm")
console.log(res);

I get the prepend element in console. But if the parent element didn't exist yet then no prepend element appears on the page and if I check the same element one second later:

setTimeout(function() {
    var res = document.getElementById("myForm")
    console.log(res);
}, 1000);

then I get null

After looping through this when the parent element finnaly gets added to the page my prepend element does not disappear.

So it looks like whatever I prepend gets added to the DOM first but then get's rejected by DOM after it is found that the parent element does not exist. But is this a normal beheavor?

It's working great.

 // When div is present jQuery(".myDiv").prepend('<div id="myForm">Content</div>'); var res = document.getElementById("myForm") console.log('mydiv:',res); setTimeout(function() { var res = document.getElementById("myForm") console.log('mydiv:',res); }, 1000); // When div is not present jQuery(".noDiv").prepend('<div id="noForm">Content</div>'); var res = document.getElementById("noForm") console.log('noForm:',res); setTimeout(function() { var res = document.getElementById("noForm") console.log('noForm:',res); }, 1000); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="myDiv"></div> 

I think you are removing the item after the item is added. It's an assumption

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