Reputation: 970
Something really weird is happening to my Rails app.
For some strange reason, jQuery does not recognise my id's in the DOM. Let me give you an example.
I have a JavaScript function as shown below:
<script>
function myFunction(){
$('#hello').toggle();
}
</script>
Simple enough, it should toggle the element with the id="hello".
But it gives me a $("#hello")
is null error. (Even though there is one in the view file)
But if I use $('hello').toggle()
instead of $('#hello').toggle()
, the expected behavior is observed.
Can somebody please tell me what is happening?
Upvotes: 0
Views: 3366
Reputation: 29
In my weird case I had two ids in one id-field of an element like: p id="id1 id2" ... and even if you try to access the right id jQuery("#id1")... this error comes up, that the object is undefined. cheers!
Upvotes: 0
Reputation: 8976
I just had this same experience and was losing my mind! But I realized that I had duplicated a previous HTML page to maintain the same format but it copied the IDs over to the new page, so jQuery got confused on which ID it was.
Remember to make your IDs unique throughout the site.
Six years late, but I hope this post helps others in the future.
Upvotes: 2
Reputation: 28765
Could it be that you (or some component) is adding the Prototype library to your page? In Prototype, you select by ID using $('id') rather than $('#id'). Also, Prototype's $() function will return null if it doesn't find a match, while jQuery's $() function will never return null.
If Prototype (or another library with a $() function) is being loaded after jQuery, it would stomp all over jQuery's version of the $() function.
If it turns out this is the case, and you can't avoid using both jQuery and the other library, you'll probably want to take advantage of jQuery.noConflict.
Upvotes: 3
Reputation: 6971
The $('hello')
selector matches on an element with a name of hello, $('#hello')
would match on an element with an id of hello. Could you have mistakenly named the element instead of applying the id?
Upvotes: 1
Reputation: 5491
Do you have that script after the html has loaded?
If not, put it inside this tag
$(document).ready(function() {
// put all your jQuery goodness in here.
});
The script could probably be executing before the HTML has loaded, hence the error.
Upvotes: 1