Home > Back-end >  Can I have two different DOM documents on same web page?
Can I have two different DOM documents on same web page?

Time:03-18

I'm studying the DOM and there is an explanation about dom here:

A web page is a document that can be either displayed in the browser window or as the HTML source. In both cases, it is the same document but the Document Object Model (DOM) representation allows it to be manipulated.

https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction

So can we have two different document on the same page?

CodePudding user response:

According to W3 schools

When an HTML document is loaded into a web browser, it becomes a document object. The document object is the root node of the HTML document. The document object is a property of the window object.

In theory, we only have 1 document (it's under window object globally) to access the entire DOM within current HTML. In the DOM, we can have multiple elements/tags which you can manipulate via document

But document is created from DocumentHTML/Document.

The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree.

Therefore, we can create a new one. Here is one example using new document injected into iframe

When do we need it? Well, I think it's rarely used and not recommended in most cases. If we try to create a new document, that will make HTML unorganizable with multiple DOM trees.

Even though in iframes, they have their own document objects

document.getElementById('frame-id').contentWindow.document

So I think we should not create a new one, if we can achieve our targets with the current document.

  •  Tags:  
  • dom
  • Related