I’m running into a weird issue with Google Docs API in Apps Script. When I try to compare two child elements using strict equality, it always returns false even when they should be the same element.
It seems like document.getChild(0) !== document.getChild(0) which is really confusing. I think the API might be creating new object instances each time instead of returning references to the same element.
How can I properly check if two child elements from separate API calls are actually the same document element?
Here’s what I’m trying:
function testComparison() {
let document = DocumentApp.getActiveDocument();
let container = document.getBody();
let firstElement = container.getChild(0);
let secondElement = container.getChild(0);
console.log(`Elements match: ${firstElement === secondElement}`);
}
Result shows:
Elements match: false
Yeah, this threw me off when I started with Google Apps Script too. The wrapper objects get recreated every API call, so comparing them directly is pointless. I use a combo approach - make a simple hash function with the element’s index and type. Something like container.getChildIndex(element) + '_' + element.getType().toString() works great as a reliable ID that won’t change between calls. When elements might move around, I’ll store the text content hash with the element type. Works really well for paragraphs with unique content. Just find properties that stay stable between API calls but are specific enough to ID your exact element.
You’re absolutely right about the API creating new object instances. I’ve hit this exact problem before - super frustrating when you first run into it. The Google Apps Script APIs don’t maintain object identity between method calls, so reference comparison just doesn’t work.
What works best is using the element’s position and type for comparison. Check if firstElement.getParent() === secondElement.getParent() and compare their indices with container.getChildIndex(firstElement) and container.getChildIndex(secondElement). If both the parent relationship and indices match, you’ve got the same element.
Another approach that’s worked well for me: compare the element’s text content and type at the same time. Check if firstElement.getType() === secondElement.getType() and if they’re text elements, compare their actual content. This has been solid for my document processing scripts where I need to track specific elements across multiple operations.
yeah, google apis are kinda strange like that. they dont return the same obj refs. i usually just write a helper that gets the unique stuff (index, type) and use those for comparison. much better than trying to match obj refs that just dont work.
This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.