dojo.withDoc provides a mechanism by which a function can have the document root temporarily changed for the execution of the function. This allows document scope changes without affecting other items in the current dojo application.


This function provides a quick way to alter the ‘document’ root as seen by dojo for specific operations. This is most notably useful when iframes are involved and you want to use a core dojo function, such as dojo.query or against contents of that iframe.


Use this function to replace the dojo.doc reference for a specific function call. Only during that specific function execution is dojo.doc assigned the document you specify. The below example demonstrates how to use it against an iframe document to query into the iframe and make updates.

Dojo 1.7 (AMD)

require(["dojo/dom", "dojo/_base/window", "dojo/dom-style", "dojo/query"], function(dom, win, style, query){
  var iframeDoc = dom.byId("someFrameId").contentWindow.document;

  // Call a callback with different 'global' values and context.
  win.withDoc(iframeDoc, function(){
    var someDiv = query("someDiv");
    style.set(someDiv, "color", "red");
  }, this));

Dojo < 1.7

var iframeDoc = dojo.byId("someFrameId").contentWindow.document;

// Call a callback with different 'global' values and context.
dojo.withDoc(iframeDoc, function(){
  var someDiv = dojo.query("someDiv");, "color", "red");
}, this));


Example 1: Using dojo.withDoc alter documents in an iFrame.


function changeStyles(){
  var button = dijit.byId("changeStyles");
  dojo.connect(button, "onClick", function(){

   // Apply styles to the document contained by the iframe
   var frameDoc = dojo.byId("simpleFrame").contentWindow.document;
   dojo.withDoc(frameDoc, function(){
     var tds= dojo.query("td");
     dojo.forEach(tds, function(cell){, "color", "red");
     }, this);
<button id="changeStyles" data-dojo-type="dijit.form.Button">Change Text Color in iFrame</button>
<iframe id="simpleFrame" name="simpleFrame" src="{{dataUrl}}dojox/data/tests/stores/books.html" style="width: 500px; height: 500px;">
Error in the documentation? Can’t find what you are looking for? Let us know!