0

In my Structure pane there are some elements that their partial name is identical, eg. image01, image03, image03 etc.

I want to know if there is a way to access them via scripting using the itemByName() method, but by providing a partial name, like in CSS i can use

h1[rel*="external"]

Is there a similar way to do this in:

var items2 = items.xmlElements.itemByName("image");
Ria S.
  • 63
  • 1
  • 11

2 Answers2

1

You could try something like the code below. You can test against the markupTag.name properties with a regular expression. The regex is equivalent to something like /^image/ in your example (find image at the beginning of a string).

function itemsWithPartialName(item, partialName) {
   var elems = item.xmlElements;
   var result = [];

   for (var i=0; i<elems.length; i++) {
      var elem = elems[i];
      var elemName = elem.markupTag.name;

      var regex = new RegExp("^" + partialName);
      if (regex.test(elemName)) {
         result.push(elem);
      }
   }

   return result;
}

itemsWithPartialName(/* some xml item */, 'image');
Josh Voigts
  • 4,114
  • 1
  • 18
  • 43
  • I must be doing something wrong because markupTag.name returns undefined. function itemsWithPartialName(partialName) { var items = app.activeDocument.xmlElements.everyItem(); var sub_items = items.xmlElements.everyItem(); var count_images = 0; for (var i=0; i – Ria S. Oct 15 '14 at 15:55
  • Try `var sub_items = items.everyItem().xmlElements;` (untested). This assumes the root element has sub elements... Can you post an example of your xml structure and what you're trying to achieve? – Josh Voigts Oct 15 '14 at 17:34
  • My structure is like that: newspaper >>cars_pa >>cars >>apartments_pa >>apartments >>image01 >>image02 >>image03 >>image04 >>image05 >>image06 >>image07.... (why can't I have a hard-return? what am I typing wrong?) Newspaper is the root element and everything else is lvl-1 child – Ria S. Oct 15 '14 at 18:19
  • See Dirk's answer which also gives a good solution with xpath. – Josh Voigts Oct 17 '14 at 18:24
1

You can use an XPath:

var rootXE = app.activeDocument.xmlElements.item(0);
var tagXEs = rootXE.evaluateXPathExpression("//*[starts-with(local-name(),'image')]");
Dirk
  • 666
  • 3
  • 6