Tom McDonnell
Tom McDonnell

Reputation: 3

Conversion of DOM element selection code to jQuery

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?

Upvotes: 0

Views: 236

Answers (3)

interjay
interjay

Reputation: 110088

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

$(inputs.submitCancel).hide().click(onClickSubmitCancel);

Upvotes: 0

Matt
Matt

Reputation: 75317

$(inputs.submitCancel).css('display', 'none');

and

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

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

Upvotes: 1

kgiannakakis
kgiannakakis

Reputation: 104168

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

var myObject = $(domElement)

With myObject you can use jQuery methods.

Upvotes: 0

Related Questions