javascript - Can't change .html() -


i have simple html (see here: http://plnkr.co/edit/nqflnfyxv2b8awsdacnu?p=preview):

<section class="divs">     <div>div1         <div>div1.1.             <div>div1.1.1</div>             <div>div1.1.2</div>         </div>         <div>div1.2.</div>     </div>     <div>div2</div> </section> 

i want go through section div:first-child elements , add mark see if belongs selector. in order implement there following code:

$(function(){     $('section div:first-child').each(function(index,element){         console.log('element.html before: '+$(element).html());         var elementhtml = '['+index+']: '+$(element).html();         $(element).html(elementhtml);         console.log('element.html after: '+$(element).html());     }); }); 

but adds [index] element's html first selector. can explain why?


upd


not quite answer, nevertheless, pete gave me understanding of problem. in order make working there necessary change

$(element).html(elementhtml); 

to

$('section div:first-child')                     .eq(index).html(elementhtml); 

it's not efficiency ofcourse, it's how solve problem in place. real solution, no doubt, use .prepend() method.

your problem first time instance of section div:first-child top level div (div1) when replace html of div, divs 2 , 3 in loop no longer exist in dom , don't updated such

instead of replacing html, prepend text:

$('section div:first-child').each(function(index, element) {   $(element).prepend('[' + index + ']: '); }); 

new plunker


Comments