3

So I had a problem where I needed a page to refresh but I couldn't use the .click() method on it because it does not work on href. I couldnt use window.location because I was trying to render a subtab which can be directly accessed due to security reasons. Then I stumbled upon this post:

https://stackoverflow.com/a/12801548/1864552

His solution works but I was hoping someone could give a good explanation on why this works.

Community
  • 1
  • 1
JS noob
  • 429
  • 5
  • 14

3 Answers3

5

jQuery click function triggers the event handlers that were bound with jQuery and simulates an event to try to trigger other click related handlers, but can't exactly reproduce the browser's native behavior :

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

If you add [0], you don't call jQuery's function but the standard DOM function, which perfectly works in this case.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
4

Because using $('#element')[0] gets the DOM element, therefore you can use javascript functions for that element

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
Anton
  • 32,245
  • 5
  • 44
  • 54
1

jQuery's $() function returns an array with special methods like:.css() and .append(). When one of these special array-functions are called jQuery applies the operation to all elements in the array. The array is made up of DOM nodes so when we access it with the array[0] syntax we get a DOM Element which has a different set of methods.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
0xcaff
  • 13,085
  • 5
  • 47
  • 55
  • 1
    Although StackEdit automatically inserts the "Written with StackEdit" line into new documents, we ask that you remove it from your answers before posting them here because it's unnecessary (Stack Exchange doesn't care what you use to write your posts as long as they are formatted properly) and therefore simply adds noise to your answers. It can even come off as promotion, which is frowned upon, even if you didn't actually create the tool yourself. Also see http://meta.stackexchange.com/questions/202156/written-with-stackedit – BoltClock Nov 01 '13 at 14:05