tags:

views:

46

answers:

2

Sorry if this is a stupid question,

I have a javascript function like:

Test.prototype.createElement = function() 
{ 
 this.oCanvas = document.body; 
 var oDiv = document.createElement('div'); 
 oDiv.style.position = "absolute"; 
this.oCanvas.appendChild(oDiv); 
return oDiv; 
}

While converting this function to jQuery, I did this:

Test.prototype.createElement = function() 
{ 
 this.oCanvas = document.body; 
 var oDiv = $('<div />').attr("postion", "absolute"); 
 $(this.oCanvas).append(oDiv); 
 return oDiv; /*  ****** This is not correct I think ******* */ 
}

or is there a better way?

+2  A: 

Your better option would be:

Test.prototype.createElement = function() 
{
    var oDiv = $('<div />').css("position", "absolute"); 
    $('body').append(oDiv); 
}

I'm assuming your element needs to be empty for a reason and needs to be tacked at the end of your document body for a reason.

Phil.Wheeler
okay but how do I return the oDiv, in original function it was a javascript object but in the converted one it is a jquery object.
Samuel
Also I have the this.oCanvas in the converted function because this was a part of a much bigger function that I truncated to show the relevant part.
Samuel
Probably a good starting point is this post: http://stackoverflow.com/questions/1302428/what-does-jquery-actually-return. It basically explains how jQuery functions always return a wrapped set. So in your javascript, you were getting back an object. You're still getting one, but now it is structured so that jQuery is able to operate further on it.
Phil.Wheeler
+1  A: 

If you want to return the actual DOM object instead of the jQuery object use:

return oDiv[0];
Jataro
I saw this using the debgger but did not find it in any reference.
Samuel
The reference in the docs is here: http://docs.jquery.com/Core/get#index
Jataro