Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the dom tree of child window?

Tags:

javascript

I open a new window using the following code:

purchaseWin = window.open("Purchase.aspx","purchaseWin2", "location=0,status=0,scrollbars=0,width=700,height=400");

I want to access the dom tree of the purchaseWin, e.g.

purchaseWin.document.getElementById("tdProduct").innerHTML = "2";

It doesn't work. I can only do this:

purchaseWin.document.write("abc");

I also try this and it doesn't work too:

 $(purchaseWin.document).ready(function(){

     purchaseWin.$("#tdProduct").html("2");

   });

What should I do?

like image 437
Billy Avatar asked Aug 11 '09 05:08

Billy


People also ask

How do I access DOM tree?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

How do you find the parent element in a child window?

You just need to prefix “ window. opener. ” and write the same code that you will write in the parent window's HTML page to access its elements.

Is the window object part of the dom?

The window object is not part of the DOM. It is a host object implemented as the "global object" to complete an ECMAScript implementation. It has its own standard which is available from the W3C.

How do I close the child window from the parent window?

A child window opens as separate window as a tab. Go back to the parent and click “Close child” and the child window closes. Viola!


2 Answers

With jQuery, you have to access the contents of the document of your child window:

$(purchaseWin.document).ready(function () {
  $(purchaseWin.document).contents().find('#tdProduct').html('2');
});

Without libraries, with plain JavaScript, you can do it this way:

purchaseWin.onload = function () {
  purchaseWin.document.getElementById('tdProduct').innerHTML = '2';
};

I think that the problem was that you were trying to retrieve the DOM element before the child window actually loaded.

like image 198
Christian C. Salvadó Avatar answered Oct 12 '22 18:10

Christian C. Salvadó


Maybe the load event of jQuery works for you as this worked for me in a similar Problem, whereas the ready event did not work:

$(purchaseWin).load(function(){
    purchaseWin.$("#tdProduct").html("2");
});
like image 39
Gunni Avatar answered Oct 12 '22 19:10

Gunni