I posted a similar question earlier and received some good suggestions. After further investigation, I found that the behavior is different enough to warrant a new question.
I am looking for suggestions as to the best way to debug some odd jQuery behavior.
The following code sample works as expected here when appending to the ul by either ID or class reference.
<input type="submit" id="submitID" value="ID" />
<input type="submit" id="submitClass" value="Class" />
<ul id="myList" class="myClass">
<li>first list item</li>
<li>second list item</li>
<li>third list item</li>
</ul>
<script>
$('#submitID').click(function(){
$('#myList').append('<li>fourth list item</li>');
});
$('#submitClass').click(function(){
$('.myClass').append('<li>fourth list item</li>');
});
</script>
However, in my application, I am unable to append using the #myList ID reference and I can't figure out why. I am dynamically rendering the ul and li elements and I have tried, as suggested, to use the following approach instead of the click event:
<script>
$('#submitID').live('click', function(){
$('#myList').append('<li>fourth list item</li>');
});
$('#submitClass').live('click', function(){
$('.myClass').append('<li>fourth list item</li>');
});
</script>
In FireBug console, I can interact with the object using .myClass, but not #myList. For example, typing the following into FireBug console:
>>$('#myList').hide()
does not hide the #myList element as I would expect. The console simply returns [].
Any suggestions are appreciated.
There are only five reasons I know of that addressing an ID won't work:
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 what you really expect to be in the page.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With