Weird stuff happening with child objects in Google Docs script
I’m scratching my head over this. When I try to compare two child objects from the same parent, they’re not equal. What’s going on?
function checkChildren() {
var document = DocumentApp.openById('your-doc-id');
var mainContent = document.getBody();
var firstKid = mainContent.getChild(0);
var alsoFirstKid = mainContent.getChild(0);
Logger.log('Are they the same? ' + (firstKid === alsoFirstKid));
}
This logs ‘false’. Huh?
Is the script giving us copies instead of references? If so, how can we check if two children are actually the same object?
I’m totally confused. Any ideas what’s happening here and how to work around it?
i get why ur confused, it’s def weird behavior. the thing is, google apps script creates new wrapper objects each time u call getChild(). so even tho they point to the same element, theyre not the same object in memory.
to compare, try using the element’s unique ID instead:
This is indeed a tricky behavior in Google Apps Script. The reason for this unexpected result lies in how Apps Script handles object references. Each call to getChild() creates a new wrapper object, even if it’s referencing the same underlying element.
To effectively compare child elements, you need to look at their content or unique identifiers rather than the wrapper objects themselves. Here’s an approach I’ve found useful:
function compareChildren() {
var doc = DocumentApp.openById(‘your-doc-id’);
var body = doc.getBody();
var child1 = body.getChild(0);
var child2 = body.getChild(0);
This method compares both the type and ID of the children, giving you a more reliable equality check. It’s a bit more verbose, but it sidesteps the wrapper object issue entirely.
I ran into this exact issue a while back, and it drove me nuts! Here’s what I discovered:
Apps Script doesn’t return the same object reference when you call getChild() multiple times. Instead, it creates new wrapper objects each time.
The workaround I found is to compare the element IDs instead of the objects themselves. Try something like this:
function checkChildren() {
var document = DocumentApp.openById('your-doc-id');
var mainContent = document.getBody();
var firstKid = mainContent.getChild(0);
var alsoFirstKid = mainContent.getChild(0);
Logger.log('Are they the same? ' + (firstKid.getId() === alsoFirstKid.getId()));
}
This should log ‘true’ if they’re actually the same child element. It’s not as clean as direct object comparison, but it gets the job done. Hope this helps!