Last week, I wrote a function that loops through all the characters in the first paragraph of a Google Doc. But chances are, if you’re running through all the characters in a paragraph, you’re going to need all the characters in all the paragraphs.
How the heck do you do that?
getNumChildren(). That’s how.
Let’s talk about the MultiColor Function. This is a function that makes every character in a Google Doc a random color. You know, in case you want your English Lit paper to look like it’s on mushrooms.
It requires three For Loops, one circling through the body to get each paragraph, one circling through each paragraph to get the text, and one circling through the text to get individual characters and assign a font color.
Basically, this is the framework using .getNumChildren to determine how many times to run each loop:
var doc = DocumentApp.getActiveDocument(); var body = doc.getBody(); for(var i=0; i<body.getNumChildren(); i++) { var par = body.getChild(i); for(var y=0; y<par.getNumChildren(); y++) { var txt = par.asParagraph().getChild(y); var len = txt.asText().getText().length; for(var x=0; x< len; x++) { string = txt.asText().getText().charAt(x); //Now you can run code on string variable to change up each character }; }; };
What's lovely about this set-up is that it won't matter if you have one paragraph or 100. body.getNumChildren() will count the paragraphs for you and adjust as necessary.
This is getNumChildren() at work in the MultiColor Function:
Here it is in a gist.
The effect? Well, if you run it while riding out a sugar high with a relatively fast internet connection, you can get a gif like this one by manically screenshoting in less than 2 minutes.