“It is necessary to detach the element” error in google docs script

北战南征 提交于 2019-12-24 10:47:01

问题


When I try to copy paragraphs form one doc to another I get unexpected error:

It is necessary to detach the element

What does it mean? What am I doing wrong?

function test_copy_paragrahps() {
  var final = 'final';
  var doc1 = get_doc('', final);
  var doc2 = create_doc_in_path('', final+'test');
  var body1 = doc1.getBody();
  var body2 = doc2.getBody();
  var par1 = body1.getParagraphs();
  for (var i=0;i<par1.length;i++) {
    body2.insertParagraph(i, par1[i]);
  }
}

here is video http://youtu.be/1WdCD5ATiYw

P.S. You can not mention on get_doc and create_doc_in_path implementations. Both return Document object.


回答1:


You attempted to insert a paragraph that already has a parent Body. You need to create a detached copy of the paragraph before you can insert it.

See this part of the documentation that mentions detaching a paragraph.

I believe this will fix the error:

function test_copy_paragrahps() {
  var final = 'final';
  var doc1 = get_doc('', final);
  var doc2 = create_doc_in_path('', final+'test');
  var body1 = doc1.getBody();
  var body2 = doc2.getBody();
  var par1 = body1.getParagraphs();
  for (var i=0;i<par1.length;i++) {
    body2.insertParagraph(i, par1[i].copy()); //--- copy()
  }
}


来源:https://stackoverflow.com/questions/25474813/it-is-necessary-to-detach-the-element-error-in-google-docs-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!