0

I'm having some difficulty selecting the a element inside the second li via jquery.

<ul id="pf-filters" class="pf-option-set clearfix" data-option-key="filter">
 <li>
  <a class="selected" href="#filter" data-option-value="*">Everything</a>
 </li>            
 <li>
  <a href="#filter" data-option-value=".current">Current</a>
 </li>
 <li>
  <a href="#filter" data-option-value=".world">World</a>
 </li>
</ul>

Via jquery I'm trying to select it by doing:

$("#pf-filters li:nth-child(2) a").click();

but i'm not getting (the filter in this case) to change. If you need more details about the problem please ask.

wadge
  • 428
  • 5
  • 18
  • 1
    your id is `#pf-filters`, not `#pf-items`. Is it a typo? – Fabrizio Calderan Apr 15 '15 at 09:32
  • `.click()` will only invoke the click events bound with it. If you want to invoke the natural click then you have to do,`$("#pf-items li:nth-child(2) a")[0].click();` – Rajaprabhu Aravindasamy Apr 15 '15 at 09:33
  • @RajaprabhuAravindasamy thanks, that solves it, but I'm curious, why the [0] in front of the selector? Its the first time seeing that kind of syntax. – wadge Apr 15 '15 at 09:37
  • @ddrjm This may help you, http://stackoverflow.com/questions/20782534/why-jquery-cannot-trigger-native-click-on-an-anchor-tag and http://stackoverflow.com/questions/773639/how-can-i-simulate-an-anchor-click-via-jquery – Rajaprabhu Aravindasamy Apr 15 '15 at 09:39
  • @RajaprabhuAravindasamy from what I gather, its use is to select the actual DOM element instead of a event handler? is this correct? – wadge Apr 15 '15 at 09:46
  • @ddrjm Yes it is used for grabbing the javascript object present underneath the jquery object – Rajaprabhu Aravindasamy Apr 15 '15 at 09:48

1 Answers1

0

$("#pf-items li:nth-child(2) a")[0].click();

Its the answer. Check the comments to my question to understand why.

wadge
  • 428
  • 5
  • 18