Tip: Simplify your appendElement

Thursday, March 13, 2008 at 11:59 PM



Many developers create new elements at runtime by using appendElement() and a string that contains the complete structure of the element.

But if you add an element with text content, such as a label, the text may contain invalid characters. For example the following code will break because the '>' in the text is invalid in an XML string and therefore cannot be used in appendElement().
  view.appendElement("<label name=\"testlabel\" x=\"0\" y=\"0\" width=\"150\"
height=\"18\">Math: 42 > 23</label>");
A safer alternative is to add the element without specifying its attributes. Then set the attributes by invoking methods upon the object that was returned by appendElement().
  // Add the empty label
var lbl = view.appendElement("<label />");

// Fill the attributes
lbl.x = 0;
lbl.y = 0;
lbl.width = 150;
lbl.height = 18;
lbl.innerText = "Math: 42 > 23";
This object-oriented approach not only eliminates the problem with invalid XML strings, but also makes your code easier to write and read, since you don't need all those escaped quotation marks (\").

Have a tip you'd like to share? Send it to gd-developer AT google DOT com. To see all tips, choose the Tips label.

1 comment:

Carlos Maidana said...

Excellent, useful and Clearly example. Thanks a lot.