Tuesday, June 10, 2014

how to cherry pick which children to manipulate with jQuery

<div id="x">
   <div>
      <span>Widget Count:</span>
   </div>
   <div>
      <span>PLACEHOLDER</span>
   </div>
</div>

 
 

Lets say we want to latch onto the outermost div above by its id and then reach down to the span containing "PLACEHOLDER" and swap out its copy. The way NOT to it is like so:

$('#x').children(2).children(1).html(count + " widgets");

 
 

What is immediately above will end up replacing the copy in BOTH span tags. The way to approach this challenge is like this:

$('#x').children().eq(1).children().eq(0).html(count + " widgets");

 
 

This reaches to ONLY the second child of the element decorated with the id of "x" and then reaches to the first child of the second child. There is another problem in that we could have "1 widgets" as a nonsensical note, but that is another thing for another blog posting perhaps. :)

No comments:

Post a Comment