59

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Vahid
  • 3,384
  • 2
  • 35
  • 69
  • 1
    What if you use "this" instead of "$(this)" as parameter? – Rob Oct 14 '11 at 12:33
  • 2
    There's nothing wrong with your code as written, so I suggest it's an error somewhere else. What do you mean by, "It didn't work"? – Tim Rogers Oct 14 '11 at 12:46
  • I have use "this", but It doesn't work either. When I see $this and thisObj in Firebug it shows this: {$this = input.focus} but {thisObj = [input.focus]} ... Is there any difference? – Vahid Oct 14 '11 at 17:55
  • @Natasha did you solve this problem? – simple guy Dec 14 '17 at 02:21

4 Answers4

83

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>
Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
erimerturk
  • 4,230
  • 25
  • 25
17

jQuery will automatically invoke your function with the proper context set.

$('#button').on('click', myFunction);

function myFunction() {
    var that = $(this);
    console.log(that);
}
Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
Muhammad Tahir
  • 2,351
  • 29
  • 25
2

If you work in no-conflict mode (i.e. out of global scope), one of the possibilities is:

jQuery.noConflict();

(function ($) {
    $('#button').on('click', myFunction);
}(jQuery));

// or
jQuery('#button').on('click', myFunction);

function myFunction() {
    var that = jQuery(this);
    console.log(that);
}
Krzysztof Przygoda
  • 1,217
  • 1
  • 17
  • 24
-1

You can pass the id to the function. With your loop inside the function.

myFunc(this.id);

function myFunc(thisid) {
    $("#" + thisid).parent().parent().children().each(function(){
        // do something
    });
}

I would normally do the loop outside the function like below:

$(this).parent().parent().children().each(function(){
    myFunc(this.id)
});

function myFunc(thisid) {

    // do something example
   $("#" + thisid).html("Yay, i changed the html for element: " + thisid);
}