SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Threaded View

  1. #1
    SitePoint Member
    Join Date
    Jun 2012
    0 Post(s)
    0 Thread(s)

    Please help me understand this JavaScript function...

    This function is from JavaScript:The Definitive Guide - 6th Edition, page 374:

    * Return the nth element child of e, or null if it doesn't have one.
    * Negative values of n count from the end. 0 means the first child, but
    * -1 means the last child, -2 means the second to last, and so on.
    function child(e, n) {
      if (e.children) { // If children array exists
      if (n < 0) n += e.children.length; // Convert negative n to array index
      if (n < 0) return null; // If still negative, no child
      return e.children[n]; // Return specified child
      // If e does not have a children array, find the first child and count
      // forward or find the last child and count backwards from there.
      if (n >= 0) { // n is non-negative: count forward from the first child
      // Find the first child element of e  <<<---------------------------  This is where code starts to get confusing to me
      if (e.firstElementChild) e = e.firstElementChild;  //    <<<----------- e.children must not exists if we are executing this line of code, so why check for Elements on e again? Maybe he meant to check 'firstChild'?
        else {  <<<--------------------------- if author knows at this point that e argument is not actually an element
        for(e = e.firstChild; e && e.nodeType !== 1; e = e.nextSibling) //  <<<----------- Why does he look for an element here by running loop until nodeType !== 1 ? TextNodes and CommentNodes will never contain Elements
        /* empty */;
        return sibling(e, n); // Return the nth sibling of the first child
      else { // n is negative, so count backwards from the end
      if (e.lastElementChild) e = e.lastElementChild;
      else {
      for(e = e.lastChild; e && e.nodeType !== 1; e=e.previousSibling)
      /* empty */;
      return sibling(e, n+1); // +1 to convert child -1 to sib 0 of last
    At the line of JavaScript code that I have pointed out above the author has already determined that the element passed is not actually an element so it must then be a TextNode(3) or CommentNode(8). So why does he run a loop looking for a NodeType == 1 on the childNodes of argument e? I may be missing something here but if somebody could show me what it is, that would be great. Thanks for reading.
    Last edited by ig-88; Jul 31, 2012 at 09:27. Reason: because I proofread after I post


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts