I’m unable to load plain HTML into a dynamically created DIV element. My script looks as follows:
$("button").click(function () {
var divElem = $('<div />').load('@Url.Action("MyFunkyPartialView", "Home")');
});
MyFunkyPartialView action method returns a partial view that looks as follows:
Where does your newly created
DIVelement go?When you create an HTML element (i.e.
$('<div/>')), that’s not automatically inserted into the document, so you can’t see it on the screen yet. You’ll have to specify where you want to put it.It is, however, already in memory, so you can already manipulate it and do stuff to it, including adding content to it as you’re doing. Nothing wrong with your call to
.load().Long story short then, is that you’re doing nothing wrong — you’re just missing a step in your workflow.
The only thing you have to do, then, is to insert the
DIVto your document. You can do that using something like:This adds the
DIVelement inside the#mainelement, after all it’s original content.EDIT
When accessing the
DIV‘s contents, we have to make sure that the.load()call has had a chance to complete first. Normally this is best achieved through thecompletecallback.