0

I have a set of button tags on a webpage and I want to get one particular button tag whose innerText is "Save". (It has no id to it.) So I have this code

var tags = document.getElementsByTagName("button");
for (var i = 0; i < tags.length; i++) {
    if (tags[i].innerText === 'Save') {
        tags[i].click();
        break;
    }
}

which works perfectly when I try it in chrome console. But I can't include this in my jelly file(which is an xml markup that will be processed into html; something like a jsp.)

The problem is with the "<" operator in the for loop which is causing this

SAXParserException: "The content of elements must consist of well-formed character data or markup."

And I learnt not to use for..in loops with arrays. What can I do? Please suggest me some workaround.

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
Vigneshwaran
  • 3,265
  • 6
  • 23
  • 36

4 Answers4

6

You are solving the wrong problem. Your problem is "Including a < character in XML breaks the XML". You need to find out how to include such a character correctly, not avoid having one ever appear in your data. There is no need to avoid a standard for loop.

Either wrap that section with CDATA markers (which stop XML special characters (except the end of CDATA sequence) being special) or represent the < with &lt; in the XML.

<![CDATA[
for (var i = 0; i < j; i++) {
    etc(i);
}
]]>

or

for (var i = 0; i &lt; j; i++) {
    etc(i);
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Wow. So quick! I used the CDATA thing so the code will be more readable. Thanks for enlightening me on how to solve the real problem. – Vigneshwaran Apr 19 '12 at 06:19
2

You can iterate with the new Array.forEach method, but it's available from JavaScript 1.6 only:

var tags = Array.prototype.slice.call(document.getElementsByTagName("button"));
tags.forEach(function (tag) {
  // ...
});

But the real solution would be to put your code into <![CDATA[]]>:

<code>
<![CDATA[
var tags = document.getElementsByTagName("button");
for (var i = 0; i < tags.length; i++) {
  // ...
}
]]>
</code>
KARASZI István
  • 30,900
  • 8
  • 101
  • 128
1
var limit = tags.length;

//loop until 0 (which is false)
while(limit) {
    if (tags[tags.length-limit].innerText === 'Save') {
        tags[tags.length-limit].click();
        break;
    }
    limit--;
}
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 1
    This is the right answer for my wrong question. As Quentin and others pointed out, I was trying to solve the wrong problem and they gave me the correct solution. Anyways thanks for your answer. – Vigneshwaran Apr 19 '12 at 06:30
0

Put it inside <[CDATA[ ... ]]>

Editing: Wrong syntax...

Fender
  • 3,055
  • 1
  • 17
  • 25