jQuery can't access a DOM element using ID but can with .class

There are only five reasons I know of that addressing an ID won't work:

  1. That ID is not really in the page like you think it is.
  2. The element with that ID hasn't been loaded yet.
  3. That ID is in the page more than once.
  4. Your aren't actually requesting the ID you think you are.
  5. Your ID contains invalid characters.
  6. The element is in an iframe or frame. Since this is actually a separate document from the parent document, searching some other document will not find elements in an embedded iframe. You would have to search the iframe itself.

To check on the first item, if it's static HTML, then do a View/Source and make sure you have in the page what you really expect to be there.

If it's dynamically generated HTML, then you will need to break in the debugger at a point where the object has been created and use the object inspector to make sure that it's really there with the appropriate ID.

Remember that IDs can only exist once in the page. If there is more than one object with the same object, then getElementById or $("#xxxx") is undefined and will not return reliable results.


You probably have 2 elements with the same ID.


try putting the functions inside $(document).ready to make sure the DOM elements are loaded, like this:

<script>
    $(document).ready(function() {

        $('#submitID').click(function(){
            $('#myList').append('<li>fourth list item</li>');
        });

        $('#submitClass').click(function(){
            $('.myClass').append('<li>fourth list item</li>');
        });

    });
</script>

Hope this helps...