Jquery parent / child selector to count <li>
I have this part of HTML
<div id="fileTreeInviati"> <ul class="php-file-tree"> <li class="pft-directory"> <a href="#" class="" name="101">A006 - SOMETEXT (<span name="contaNew"></span>)</a> <img src="./moduli/home/images/info.png" title="Informazioni Azienda" class="imgInfo"/> <ul style="display: none;"> <li class="pft-file ext-png"> <a href="javascript:getInfoFile('4');" class="" id="4">cut.png</a> </li> <li class="pft-file ext-dll"> <a href="javascript:getInfoFile('27');" class="new" id="27">Safari.dll</a> </li> </ul> </li> <li class="pft-directory"> <a href="#" class="" name="102">A012 - SOMETEXT (<span name="contaNew"></span>)</a> <img src="./moduli/home/images/info.png" title="Informazioni Azienda" class="imgInfo"/> <ul style="display: none;"> <li class="pft-file ext-jpg"> <a href="javascript:getInfoFile('19');" class="new" id="19">04.jpg</a> </li> <li class="pft-file ext-dll"> <a href="javascript:getInfoFile('24');" class="new" id="24">Safari.dll</a> </li> </ul> </li> <li class="pft-directory"> <a href="#" class="" name="103">A014 - SOMETEXT (<span name="contaNew"></span>)</a> <img src="./moduli/home/images/info.png" title="Informazioni Azienda" class="imgInfo"/> <ul style="display: none;"> <li class="pft-file ext-txt"> <a href="javascript:getInfoFile('17');" class="new" id="17">acu.txt</a> </li> <li class="pft-file ext-dll"> <a href="javascript:getInfoFile('22');" class="new" id="22">Safari.dll</a> </li> </ul> </li> </ul> I am working on a js fragment that cycles through all "a" from "li" and checks to see if it has a class of "new" if it increments the counter by one. This counter should now be printed at the relative level "li" "span" 3 earlier. Therefore, I have an element number with a "new" class. Js fragment is
$("#fileTreeInviati .php-file-tree .pft-directory li").each(function(){ $(this).children("a").each(function(i,e){ if ($(e).hasClass("new")){ cont++; console.log($(e).text()); $(this).parent().parent().parent().children("a").children("span").text(cont); } }) cont = 0; });
I think I'm almost there, but the counter is always 1. I think there is something unpleasant with .children, maybe it can only cope with the first entry? thanks for the help
+4
2 answers
Ok, I'm figuring out how to do magic :) Here it is:
cont = 0; $('#fileTreeInviati .php-file-tree .pft-directory').each(function() { $(this).children("ul").children("li").children("a.new").each(function(i,e){ cont++; $(e).parent().parent().parent().children("a").children("span").text(cont); }); cont=0; }); Now everything works fine. If you think this can do better, you know. Bye
+1