1

I would just like to know what $(this) refers to when you use it within a function called by a button.

Is it referring to the button element or is it referring to the function itself.

Code example:

<div>
<span class="fileError"></span>
<input type="file" class="understanding" />
</div>

<script>
$('.understanding').click(function(){

   $(this).closest('div').find('span.fileError').html('My brain needs help');
});
</script>

Things I have tried to change the html of my span

$(this).prev('span.fileError').html();

$(this).closest('div').find('span.fileError').html();

$(this).closest('div').find('span.fileError').text();

Links I have tried:

Jquery:find input field closest to button

Understand javascripts 'this' with clarity

Finding Closest p tag to the clicked button

I have look at more places, thought I would just show those I found most informing. What do I need to do here and to what $(this) is referring within the function?

halfer
  • 19,824
  • 17
  • 99
  • 186
Jelly Bean
  • 1,161
  • 1
  • 11
  • 22

2 Answers2

4

Is it referring to the button element or is it referring to the function itself.

In jQuery event handler functions, this refers to the DOM element itself, and $(this) wraps that in a jQuery object.

But the real answer to your question of how to change the HTML of your span is going to depend on what fileupload is.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • fileupload is a function that runs my upload ajax when the file input is clicked. so in this case any errors that are returned should be written to that span. I hope this provides some clarity. – Jelly Bean Sep 14 '18 at 09:35
1

It depends on what kind of function will you use as event handler:

  • arrow function takes this from the outer scope
  • normal function has this assigned to a current element when used as an event handler.

$('.understanding-arrow').click(() => {
  console.log(this === window && "this is window");

  $(this).closest('div').find('span.fileError').html('My brain needs help');
});
$('.understanding-normal').click(function() {
  console.log(this === $('.understanding-normal')[0] && "this is input el");

  $(this).closest('div').find('span.fileError').html('My brain needs help');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <span class="fileError"></span>
  <input type="button" class="understanding-arrow" value="arrow function" />
</div>
<div>
  <span class="fileError"></span>
  <input type="button" class="understanding-normal" value="normal function" />
</div>
marzelin
  • 10,790
  • 2
  • 30
  • 49