jQuery Passing $(this) to a Function

JqueryThisParameter Passing

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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>

Solution 2 - Jquery

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

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

function myFunction() {
    var that = $(this);
    console.log(that);
}

Solution 3 - Jquery

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);
}

Solution 4 - Jquery

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);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVahidView Question on Stackoverflow
Solution 1 - JqueryerimerturkView Answer on Stackoverflow
Solution 2 - JqueryMuhammad TahirView Answer on Stackoverflow
Solution 3 - JqueryKrzysztof PrzygodaView Answer on Stackoverflow
Solution 4 - JqueryShaun O'TooleView Answer on Stackoverflow