I have a dozen collapsible list (like the following) and each gets a bunch of dynamically created ‘li’s:
<div data-role="collapsible" data-collapsed="true" data-theme="b" data-content-theme="b">
<h3>Community Alerts
<span id="comm_count" class="ui-li-count" style="float:right;">0</span></h3>
<ul id="communityAlertList" data-role="listview"></ul>
</div>
When a user does a taphold on one of the ‘li’s I want to delete it the ‘li’ (that parts working) and then I need to update/reduce the ui-li-count. To find the span and get its content I’m using the following:
var ui_li_count = $(this).closest('span')
var count = $(ui_li_count).textContent; // also tried innerHTML
alert("Count = " +count);
count--;
$(ui_li_count).html(count);
The alert shows “Count = undefined”.
How do I find and retrieve the textContent?
The problem is your use of
.closest(). The way.closest()works is to find the closest parent/child, fanning out away from the (this) element. In your code there is no span element that is a direct parent/child of an<li>, so it returns undefined.To put it simply using jquery selectors, the span you want to get is nested like so from your li:
However we don’t really want to use all those selectors, so we could just do this:
Because the
h3is on the same level as yourul, we first need to get it’s container which in your example is adiv. Then we use find, to find the span within that div.Also note that i used
.text()to get the content. This is the jQuery alternative to javascripts.textContent.Made a simple test case so you can see it working with your code:
http://jsbin.com/odamac/3/edit
Hopefully this will point you in the right direction 🙂
UPDATE
One more problem your going to run into is that your DOM is not exactly laid out how you think it is. jQuery Mobile inserts extra elements into the page when the window loads so that it can implement it’s functionality.
Your actual page DOM looks something like this:
Notice the extra and elements that jQuery Mobile has inserted to make the collapisible functionality work. You will need to account for these elements when traversing the DOM using
closest();,find();,parent();,children();, etc.