[jQuery] Potential Bug when .append (ing) html and then selecting on it?
I have the follow HTML markup
<h4 class="filteredResultsTitle">Information Sources</h4>
<ul style="display: block;">
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
I'm trying to create show/hide buttons against the 'Information
Sources' <h4> element to toggle the <ul> element to disappear/
reappear. So far I have the following jquery....
$(document).ready(function()
{
$('h4.filteredResultsTitle').each(function()
{
$(this).append(' <span class="show">(<a href="#">show</a>)</
span>');
$(this).siblings('ul').hide();
$(this).children('span a').click(function()
{
$(this).parent().parent().siblings('ul').show();
$(this).text('hide');
return false;
});
});
});
This doesn't seem to work though. However, if I change $(this).parent
().parent().siblings('ul').show(); into $(this).parent().siblings
('ul').show(); (remove a call the .parent() ) it does work, but surely
this is incorrent as the markup is...
<h4>Title <span class="show">(<a href="#">show</a>)</span></h4>
...and the parent of <a> is <span> and the parent of <span> is <h4>,
yet it seems to jump straight from <a> to <h4> missing out the <span>
when I remove a call to .parent(). What's more my click event is
getting applied to the <span> and not the <a> as $(this).text('hide')
causes the brackets and the <a>show</a> to be completely replaced.
I remember a work colleague telling me that JQuery does have problems
trying to select on elements that have been dynamically created (such
as when using .append() in my case). Is this a know issue with JQuery,
or am I totally doing something wrong.
Cheers!