tags:

views:

1699

answers:

2

I am creating an element with document.createElement(). Now how can I pass it to a function that only takes a Jquery object?

$("#id")

I can not use it, as the element has not been rendered in the page yet.

+17  A: 
var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element
Marius
This works because jquery will take not only a string selector, but an existing jquery object, or any valid dom object as an argument to the main $() query function.
Samuel Meacham
What about the reverse? You have a jquery element and want to convert it to a dom element?
Aros
The reverse can be done by: http://johnjianfang.blogspot.com/2009/04/convert-jquery-object-to-dom-object.html
Aros
+8  A: 

What about constructing the element using jQuery? e.g.

$("<div></div>")

creates a new div element, ready to be added to the page. Can be shortened further to

$("<div>")

then you can chain on commands that you need, set up event handlers and append it to the DOM. For example

$('<div id="myid">Div Content</div>')
    .bind('click', function(e) { /* event handler here */ })
    .appendTo('#myOtherDiv');
Russ Cam
actually i am getting the element from somewhere where i cant change the code
Tanmoy