jQuery Passing $(this) to a Function

Vahid picture Vahid · Oct 14, 2011 · Viewed 81.5k times · Source

I have lines of code like this:

$(this).parent().parent().children().each(function(){
    // do something
});

It works well. But I need to run these lines multiple times. So I have created a function and pass $(this) parameter to a function:

myFunc( $(this) );

function myFunc(thisObj) {
    thisObj.parent().parent().children().each(function(){
        // do something
    });
}

But in this way, It didn't work.

Answer

erimerturk picture erimerturk · Oct 14, 2011

you can check this link.

http://jsfiddle.net/zEXrq/38/

$("#f").click(function() {
  myFunc($(this));
})

function myFunc(thisObj) {
  thisObj.parent().parent().children().each(function() {
    alert("childs")
  });
}
<div id="wordlist">
  <div id="a"></div>
  <div id="b">
    <div id="e"></div>
    <div id="f">child</div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>