Why am I getting Uncaught TypeError: Object #<an HTMLSelectElement> has no method 'find'?

despot picture despot · Dec 7, 2010 · Viewed 13.7k times · Source

Why am I getting:

Uncaught TypeError: Object # has no method 'find' (anonymous function):8080/twolittlesheep/js/sizeColorDependancy.js:16 c.event.handleajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:63 c.event.add.h.handle.oajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js:56

when I try to run a simple jQuery script? The script falls at the line where I use the find method in the next jquery code snippet:

$(document).ready(function(){
  $("select#p_sizesId").change(function(){
   var $colorsSelect = $("select#p_colorsId")[0];
   $("select#p_colorsId")[0].find('option').remove().end().append('<option selected="selected" value="whatever">text</option>');
  });
});

In my head tag in the html I have:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<%-- <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script> --%>
<script type="text/javascript" src="js/sizeColorDependancy.js"></script>

I am using Google Chrome (together with Developer Tools).

All that I found as an explanation in another thread was that when using Chrome's developer tools, the problem arises. But I was running the code without using the Developer Tools and the same happened (the script didn't do anything => the error occurred).

Answer

Nick Craver picture Nick Craver · Dec 7, 2010

When you do [0] you're getting the first element from the selector matches as a DOM element, not a jQuery object which has .find(), just remove [0], like this:

$(document).ready(function(){
  $("#p_sizesId").change(function(){
   $("#p_colorsId").find('option').remove().end().append('<option selected="selected" value="whatever">text</option>');
  });
});

A few other notes, when using a #id selector, don't prefix it unless absolutely needed, it slows things down. Also since ID's should be unique, there should be no need for getting the first element. The selector should only match 1 or 0 elements. If they're not unique, don't use ID's instead use classes.