Today I suddenly wanted to review the principles of making a rich text editor. So I started doing it step by step without saying a word. Because I wrote a simple rich text editor a year ago, I probably still have some impressions. But when I ran the code I wrote, I found a problem:
var ifr = document.createElement('iframe');
ifr.width = 300;
ifr.height = 300;
var idoc = ifr.contentDocument || ifr .contentWindow.document;
idoc.designMode = 'on';
idoc.contentEditable = true;
idoc.write('');
document.body.appendChild(ifr);
Take a look at the code above. Have you found any errors?
I think if there are no children who have had similar experiences to me, they probably won’t be able to see what’s wrong with this code. So you might as well go for a run, maybe you will find the problem soon.
Let me reveal the answer below:
This code will throw an object not found exception. Which object cannot be found? The document object cannot be found, what? How is it possible that the document object cannot be found? Of course, this document object is the document object of the iframe. Anyone who has done rich text knows that you must first obtain the document object of the iframe before making it editable. But why can't we get the document object? I won’t be too pretentious here. Let me talk about my solution process.
First of all, I went to Google and found that the way I got the document was correct. Then I wondered if it was Chrome? Doesn't Chrome support these two objects? So I switched to Firefox. The result is still the same. Then what is certain is that it must be a problem with your own code.
Later, by comparing the code on the Internet, I found that the position of my appendChild was a bit wrong, so I moved it ahead of time to get the document object:
var ifr = document.createElement('iframe');
ifr.width = 300;
ifr. height = 300;
document.body.appendChild(ifr);
var idoc = ifr.contentDocument || ifr.contentWindow.document;
idoc.designMode = 'on';
idoc.contentEditable = true;
idoc.write('');
The results ran smoothly. Then I analyzed the error this time. In fact, the reason for this error is very simple. Everyone knows that an iframe actually contains another document, and this document can only have a document object after it is initialized. And if the iframe element is not added to the DOM tree, the document in the iframe will not be initialized. Therefore, in our code at the beginning, the contentDocument value in the ifr variable we obtained is null, which means that the document in the iframe has not been initialized at this time.
Following this line, I checked the initialization status of other nodes and found that in fact, once other element nodes are created, they will have their own attributes and methods regardless of whether they are added to the DOM tree or not. In other words, iframe is an outlier among many element nodes.