0 Replies Latest reply on Mar 1, 2012 12:29 PM by OliverJohn

    Building an array of elements

    OliverJohn Level 2

      Rather than posting another problem that I've been having, I though I would share a function that has proven so broadly useful it has shown up in some form in at least half of the scripts I've written over the last month. The function returns an array of elements with a given name that are decendant of a given element.

       

      First, credit where credit is due. The recursive elegance of this function was directly and shamelessly stolen from one of Debra Herman's Extending Framemaker posts.

       

      //buildElemArray traverses the element tree building an array of elements with given name

      function buildElemArray(elem, targetElemName, fndElemArray)

      {

      // First argument is a FrameMaker Element object

      // Second argument is a string

      // Third argument (the array) is usually not passed from outside the function

      if (typeof fndElemArray == 'undefined') fndElemArray = new Array();

      if (elem.ElementDef.Name==targetElemName) fndElemArray.push(elem); //If passed element is a match, add to array

      var child = elem.FirstChildElement; //get first child if any

      while (child.ObjectValid())

      {

      buildElemArray(child, targetElemName, fndElemArray); //traverse subtree with child as root

      child = child.NextSiblingElement; //get the siblings

      }

      return fndElemArray;

      }

       

      //A simple example of use

      var allHeadings = buildElemArray(app.ActiveDoc.MainFlowInDoc.HighestLevelElement, "head");

      $.writeln(allHeadings.length);