jquery: can't get appendTo on parents() to work, may not understand parents() method?

143 Views Asked by At

The following code block does not work:

$("<span class=\"ideacount\">").prependTo(chapter.parents(".chapter")).each( function(index) {
    $(this).html((parseInt($(this).text() || 0)+1)+"");
});

where 'chapter' is a node that in this case is nested 5 elements deep among other elements of class 'chapter'.

Whereas this code behaves as expected, but is not what I want (it prepends to all other branches of the tree structure as well instead of just the ancestry of 'chapter'):

$("<span class=\"ideacount\">").prependTo(".chapter").each( function(index) {
    $(this).html((parseInt($(this).text() || 0)+1)+"");
});

Edit: to elaborate:

chapter.parents().length

is 10 (5 spans of class 'chapter', 5 li's)

chapter.parents(".chapter").length is 0!?

1

There are 1 best solutions below

0
On

Try closest instead of parents.

$("<span class=\"ideacount\">").prependTo(chapter.closest(".chapter")).each( function(index) {
    $(this).html((parseInt($(this).text() || 0)+1)+"");
});