Search code examples
javascriptjquerydomprepend

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, i.e. 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?


Solution

  • 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