Omar Omar - 14 days ago 4x
jQuery Question

Get ID of LI element not working when in function in Jquery

I can grab the ID of the LI element using JQuery's click function, but when I make my own function the ID of the LI element comes up undefined:

The first LI element uses Jquery's click function. The second element uses it's own function where the ID comes up undefined.


<ul id="pricerange_options" class=" options">

<li id="option1" data-value="1" class="dropdown-option">1</li>

<li id="option2" data-value="1" class="dropdown-option" onClick="chooseDropDownOption();">2</li>



function chooseDropDownOption() {

$('#pricerange_options li').click(function () {


When you attach an unobtrusive event handler in jQuery the function runs under the scope of the element that raised the event, therefore the this keyword refers to the element.

When attaching an event through an on* event attribute it runs under the scope of the window, hence this refers to the window. To fix the problem, send the element as a parameter to your function:

function chooseDropDownOption(el) {
  alert($(el).attr('id')); // or just
<script src=""></script>
<ul id="pricerange_options" class=" options">
  <li id="option2" data-value="1" class="dropdown-option" onClick="chooseDropDownOption(this);">2</li>

It should be noted though that using on* event handlers is very outdated. You should always use unobtrusive event handlers where possible.