views:

42

answers:

3

I have a large Javascript codebase to convert to jQuery. The code is structured such that DOM elements are created in Javascript (using a library called DomBuilder), and saved to variables if they will be needed later, before being added to the DOM.

Eg.

var inputs =
{
    submitConfirm: INPUT({type: 'button', value: 'Submit'}),
    submitCancel : INPUT({type: 'button', value: 'Cancel'})
};

document.appendChild(inputs.submitConfirm);

Then later for example...

inputs.submitCancel.style.display = 'none';
inputs.submitCancel.addEventListener('click', onClickSubmitCancel, false);

My problem is that jQuery seems to lack a way of manipulating DOM elements directly, as opposed to selecting them first (with for example $('#submitCancel').

Can anyone suggest a way to directly translate the last two Javascript lines given above to use jQuery, given that the DOM elements are already available, and so do not need to be selected?

A: 

Use $(elementVar) to get a jQuery object containing the DOM element. For the example you gave:

$(inputs.submitCancel).hide().click(onClickSubmitCancel);
interjay
A: 

Any DOM element can be wrapped into a jQuery object very easily:

var myObject = $(domElement)

With myObject you can use jQuery methods.

kgiannakakis
Ah! Simple! My conversion project will be as straightforward as I had hoped. Thank you all for your prompt responses.
Tom McDonnell
+1  A: 
$(inputs.submitCancel).css('display', 'none');

and

$(inputs.submitCancel).bind('click', onClickSubmitCancel);

See http://api.jquery.com/jQuery/ to see what jQuery accepts.

Matt