Tip: Simplify your appendElement
March 14th, 2008 | Published in Google Desktop API
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("");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 labelThis 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 (\").
var lbl = view.appendElement("");
// Fill the attributes
lbl.x = 0;
lbl.y = 0;
lbl.width = 150;
lbl.height = 18;
lbl.innerText = "Math: 42 > 23";
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.