issue with wrap -- Bug or Feature

issue with wrap -- Bug or Feature

In a small script I am writing I do the following:

find a div with id = 'xxx'
add a button to that div

then wrap that div in a container div.

I can separately add the button with no problem -- results show in page.
I can separately add the wrapper -- results show in the page.

However, if I do the add button followed by the wrap, the button is missing.
It looks like the wrap is accessing the div the way it was before I dynamically added the button.

I can make this work by wrapping the div first, then adding the button.

But it would be better if I could separate these two activities and not worry about which happened first.

So is this a bug or is this a feature.

Thanks
Claude