Reputation: 21019
I have a Javascript application and I need to retrieve an HTML file to template it. The way I am doing this now is:
var _$e = null;
$.ajax({
type: "GET",
url: "/static/jobs_overview.html",
async: false,
dataType: "xml",
success: function (xml) {
_$e = $(xml.documentElement);
}
});
This does seem to work, but for some reason, I am not getting a proper jQuery object in _$e
. I know that because the styling is done by jQuery is getting lost at some point, but also, when I set a breakpoint in success, here is what I see:
> _$e
[<div class="hello" style="background-color:#FFD700;height:200px;width:100px;"><p> Hi </p></div>]
> _$e.width()
TypeError: Cannot read property 'position' of null
However, when I copy the HTML string manually and convert it to a jQuery object as in success
, the output is:
> $('<div class="hello" style="background-color:#FFD700;height:200px;width:100px;"><p> Hi </p></div>').width()
100
Seems like the xml object returned isn't getting converted properly into jQuery (or not all attributes of the object are being read properly by jQuery -- given that the HTML is rendering but styling isn't).
The xml object is:
> xml
#document
<div class="hello" style="background-color:#FFD700;height:200px;width:100px;">…</div>
Any ideas how to get the xml (or the HTML file) rendered as a jQuery object properly?
Upvotes: 0
Views: 117
Reputation: 3030
Could it be because you're grabbing the datatype XML? Have you tried setting your datatype to HTML (or nothing) and just do this (ignoring the .documentElement and just assuming the whole glomp is your HTML):
$.ajax({
type: "GET",
url: "/static/jobs_overview.html",
async: false,
dataType: "html",
success: function (data) {
_$e = $(data); // we are getting back HTML,
console.log(_$e.width()); // jQuery is fine with html globs
}
});
Upvotes: 1
Reputation: 3032
This is likely because you are pulling it in as XML. Try setting the dataType
to html
and see if that makes any difference.
It also sounds like .load()
might better fit your needs: http://api.jquery.com/load/
Upvotes: 0