InnerHTML dynamically adds html code and scripts, assigns values to the innerHTML of an element, and makes the js Code in the value effective and compatible with multiple browsers. This is a great way of symptom: when setting values for innerHTML of an element, if the provided HTML code contains js scripts, these scripts are often invalid or valid in a browser, but are not valid in other browsers.
Cause: different browsers have different processing methods for inserting scripts in innerHTML. The practices are summarized as follows:
For IE, the script tag must contain the defer attribute. Secondly, the innerHTML node must be in the DOM tree at the time of insertion.
For Firefox and Opera, innerHTML nodes cannot be in the DOM tree at the time of insertion.
According to the above conclusion, a general method for setting innerHTML is provided:
The Code is as follows:
/*
* Description: cross-browser innerHTML setting method.
* HTML code that can be inserted contains scripts and styles.
* Parameters:
* El: the node in the DOM tree. set its innerHTML
* HtmlCode: The inserted HTML code
* Tested browsers: ie5 +, firefox1.5 +, and opera8.5 +
*/
Var set_innerHTML = function (el, htmlCode)
{Var ua = navigator. userAgent. toLowerCase ();
If (ua. indexOf ('msie ')> = 0 & ua. indexOf ('Opera') <0)
{HtmlCode ='
For IE
'+ HtmlCode;
HtmlCode = htmlCode. replace (/ ] *)>/Gi ,' ');
El. innerHTML = htmlCode;
El. removeChild (el. firstChild );
}
Else
{Var el_next = el. nextSibling;
Var el_parent = el. parentNode;
El_parent.removeChild (el );
El. innerHTML = htmlCode;
If (el_next)
El_parent.insertBefore (el, el_next)
Else
El_parent.appendChild (el );
}
}
The above code has another problem: If the inserted HTML code contains the document. write statement, the whole page will be damaged. In this case, document. write can be redefined to avoid this. The Code is as follows:
The Code is as follows:
/*
Description: redefines the document. write function.
When set_innerHTML is used, the inserted HTML code contains the document. write statement, causing damage to the original page.
*/
Document. write = function (){
Var body = document. getElementsByTagName ('body') [0];
For (var I = 0; I <arguments. length; I ++ ){
Argument = arguments [I];
If (typeof argument = 'string '){
Var el = body. appendChild (document. createElement ('P '));
Set_innerHTML (el, argument)
}
}
}