Federinik
Federinik

Reputation: 521

Reaching element from ID in jQuery listener

I have some HTML like this:

<select id="myselect">
  <option>...</option>
  <option>...</option>
  <option>...</option>
</select>

<div class="myclass" id="mydiv">[...]</div>

and, im my js

$("#myselect").addEvents({
  ..., 
  change: function(){
    $("#mydiv").addClass("anotherclass");
  }
  ...
});

Well, my script can't fine $("#id"), neither in the js console of Chrome Developers Tools. What's going on? Is that possible that in the listener, where the this object is the event raiser, the $("") selector doesn't work properly?

Thank you

EDIT: just a typo in the question, I forgot the # in the first selector. problem is still on.

Upvotes: 1

Views: 176

Answers (5)

billyonecan
billyonecan

Reputation: 20250

addEvents() is not a jQuery method (I believe it is MooTools), if you want to bind event handlers using the same syntax as above, use on():

$(document).ready(function() {
    $('#myselect').on({
        change: function() {
            $('#mydiv').addClass('anotherClass');
        }
    });
});

Upvotes: 0

Federinik
Federinik

Reputation: 521

I was watching just a little part o the code; now I red it and it seems to be MooTools, and not jQuery; I didn't noticed before. So, I think that's the problem.

Upvotes: 0

Michael B.
Michael B.

Reputation: 2809

Did you forget to use document ready ? because jQuery can't find elements if you try to select them before the DOM is ready.

$(document).ready(function() {
  $("#myselect").addEvents({ ....

  ... })
});

Upvotes: 0

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

You have miss # into the jquery selector
Try this:

$("#myselect").addEvents({
  ..., 
  change: function(){
    $("#mydiv").addClass("anotherclass");
  }
  ...
});

Upvotes: 1

mikach
mikach

Reputation: 2427

Maybe it must be $("#myselect") instead of $("myselect")

Upvotes: 0

Related Questions