Home > Web Front-end > JS Tutorial > body text

document.createElement() usage and precautions (not compatible under ff)_javascript skills

WBOY
Release: 2016-05-16 17:40:39
Original
1125 people have browsed it

Today I dealt with a date picker compatibility issue between IE and FF. It is difficult to find errors in this situation. It took me a long time to locate the error to document.createElement(), the method of creating elements in js. This method Support creating elements like this under IE

Copy code The code is as follows:

var inputObj = document.createElement
("");

But this situation is incompatible under ff.
Also, pay special attention to the creation of input elements: there are many elements related to input, such as: checkbox, radio, submit, reset..., so creating input is a very special usage.

The correct way to create different inputs is:

Copy code The code is as follows:



For input, e.type can either precede or follow appendChild in Netscape, Opera and Firefox. But in IE, the type attribute must come first, and other attributes must come after.

Another feature of IE when creating elements is that they can be created together with attributes, for example: var e = document.createElement(" "); This doesn't work in other browsers, so we don't support it either.

Summary:

•For non-input elements, in each browser, changes to element attributes can be written before the display element (insertBefore or appendChild), or after it.
•For input elements, in order to be compatible with IE, the type attribute is written before the display element (insertBefore or appendChild), and other attributes are written after it.
Recommended:

•Except the type attribute of the input element is written before the display element (insertBefore or appendChild), other attributes are written after the display element.
•When changing attributes, use the return value of createElement if it is written before the displayed element (insertBefore or appendChild), and use the return value of insertBefore or appendChild if it is written after the displayed element.

Copy code The code is as follows:

1.var echkbox=document.createElement("input");
2.echkbox.setAttribute("type","checkbox");
3.echkbox.setAttribute("id","inputid");
4.echkbox.setAttribute("name","inputname");
5.echkbox.setAttribute("value","inputvalue");
6.var addhere=document.getElementById("someElementId");
7.addhere.appendChild(echkbox);
8.echkbox.setAttribute("checked","checked");
9.alert(document.getElementById("inputid").checked);