0

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?

Samuel
  • 1,949
  • 4
  • 18
  • 30

2 Answers2

2

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
  • 16,748
  • 10
  • 99
  • 155
  • 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 Sep 24 '09 at 02:54
  • 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 Sep 24 '09 at 02:56
  • 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 Sep 24 '09 at 03:15
2

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

return oDiv[0];
Jataro
  • 2,548
  • 1
  • 17
  • 17