47

How can I convert a JavaScript DOM object to a jQuery object?

<tr onclick="changeStatus(this)">

function changeStatus(myObject) {
       XXX.removeClass();
}

What should I write in place of XXX? I know I can make a workaround using an id and an id selector, but it is not so elegant. Is there any way to convert a js DOM object to a jQuery object or using the this keyword in jQuery?

2 Answers 2

77
var $this = $(myObject);

$this is a jQuery object. You can create jQuery objects from DOM elements.

<tr onclick="changeStatus(this)">

function changeStatus(myObject) {
       $(myObject).removeClass();
}

I would like to recommend doing your event binding with jQuery as well:

<tr class="change-status">

$('.change-status').on('click', function () {
    $(this).removeClass( ... );
});

This is nice because now all the JS code is in one place and can be updated (in my opinion) more easily. Note that the class I added to the <tr> element is not necessary if you want to bind to all <tr> elements in the DOM.

Sign up to request clarification or add additional context in comments.

1 Comment

You are absolutely right about the event handler being in JavaScript. But there are situations where defining the event handler is not in your hand. For example a third party plugin where click event is handled by them. So your first example helped me more. Anyway perfect solution!
13

Simply wrap the pass the DOM object in as the first argument.

$(myObject).removeClass('foo');

1 Comment

Simplest. Works for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.