Aximili
Aximili

Reputation: 29474

JavaScript/jQuery: How do you pass an element to a function as its 'this'?

How do you pass something to a function, as if it calls the function?

Say I have this function

function ShowId() {
  alert($(this).attr('id'));
}

and this HTML

<div id='div1'>
  <a class='link'>Some link</a>
</div>

I want to do this

$('div .link').click(function() {
  $(this).parent('div').call(ShowId); // What is the right syntax?
});

and it should alert: div1

Upvotes: 2

Views: 73

Answers (5)

Ishan Jain
Ishan Jain

Reputation: 8171

You can pass your element as a object in your function-

$('div .link').click(function() {
  ShowId($(this).parent('div'));
});

function ShowId(Obj) {
  alert(Obj.attr('id'));
}

Try This

Upvotes: 0

Code Lღver
Code Lღver

Reputation: 15603

Use this code:

$('div .link').click(function() {
  var parentObj = $(this).parent('div');
  ShowId(parentObj); // call the function with arguments simply
});

And your function will be:

function ShowId(that) {
  alert($(that).attr('id'));
}

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123473

.call() is a method of functions, so the order is the other way around:

ShowId.call($(this).parent('div'));

Though, passing as an argument is also usually viable:

function ShowId(elem) {
    alert($(elem).attr('id'));
}
ShowId($(this).parent('div'));

Upvotes: 4

jharding
jharding

Reputation: 1414

Almost, try this:

ShowId.call($(this).parent('div'))

Upvotes: 2

Jason Evans
Jason Evans

Reputation: 29186

Pass the jQuery element:

function ShowId($this) {
  alert($this.attr('id'));
}

$('div .link').click(function() {
  $(this).parent('div').call(ShowId($(this)));
});

Upvotes: 0

Related Questions