Usage and compatibility of document. createElement in Javascript

Source: Internet
Author: User

This article will introduce the document. createElement usage in js and compatibility with some different browsers.


W3C DOM Level2 Core stipulates that the createElement method under the Document interface can create an Element Node object instance. It can input a string parameter tagName. in HTML, this parameter can be in any form, but tagName should be a legal tag name.

For example: document. createElement ("td"); // create a td

If the tagName contains invalid characters, an INVALID_CHARACTER_ERR exception should be thrown.

Due to Microsoft's strength, its product IE uses some rules other than the specifications, one of which is related to the createElement method. That is, in IE, The createElement method can not only create a Node object using a valid tag name, but also pass in a valid HTML code string as a parameter to create a Node object.

For example, document. createElement ("<input type = 'text' name = 'txtname'>"); // create an input whose name attribute is "txtName"

If you use IE's unique method of passing in a valid HTML code string for createElement as a parameter to create a Node object, an exception will be thrown in other browsers and subsequent Code cannot be executed. This causes the compatibility of the browser.

Some readers may say that using the createElement method to pass in the tag name does not solve the compatibility problem?

For example:

The Code is as follows: Copy code

Var txt = document. createElement ("input ");

Txt. type = "text ";

Txt. name = "txtName ";
......

However, in IE6 and IE7, if an input element is dynamically generated, the name attribute cannot be set for it, which is a problem of IE itself. At this time, the unique method of IE to create a Node object by passing in a valid HTML code string for createElement is a great opportunity. However, the bug that the name attribute cannot be set for input in IE has been fixed in IE8. The preceding problem does not exist in other browsers.

Therefore, to finally solve the compatibility problem of the createElement method, you should pay attention to the judgment of the browser. for IE, you can use its unique method to pass in a valid HTML code string for createElement as a parameter, non-IE browsers still use W3C standard methods.


For example:

The Code is as follows: Copy code


If ($. browser. msie ){

Var txt = document. createElement ("<input type = 'text' name = 'txtname'> ")

} Else {

Var txt = document. createElement ("input ");

Txt. type = "text ";

Txt. name = "txtName ";


}


Document. createElement () usage and precautions.

Today, I handled the compatibility problem of ie and ff for a date selector. It was difficult to find an error in this case. After a long time, I found the error and found the method document for creating elements in js. createElement (). This method supports the creation of elements in ie.

The Code is as follows: Copy code

Var inputObj = document. createElement
("<Input type = 'text' size = '8' style = 'border: 0px; border-bottom: 2px solid # c0c0c0; '" readonly> ");


However, this is incompatible with ff.
Also, pay special attention to the creation of input elements: there are many elements related to input, such as checkbox, radio, submit, reset.... Therefore, it is a special usage to create input.

The correct method to create different inputs is:

The Code is as follows: Copy code

<Div id = "board"> </div>

<Script type = "text/javascript">
<! --
Var board = document. getElementById ("board ");
Var e = document. createElement ("input ");
E. type = "radio"; // followed by the previous line
Var obj = board. appendChild (e );
Obj. checked = true;
// The following statement is correct:
// E. checked = true;
-->
</Script>

For input, e. type in Netscape, Opera, and Firefox can be before or after appendChild. However, in IE, the type attribute must be in the front, and other attributes must be in the back.

Another feature of IE creation elements is that they can be created together with attributes, such as var e = document. createElement ("<input type = 'Radio 'name = 'r' value = '1'/>"); this is not supported in other browsers.

Summary:

• For non-input elements, each browser can write changes to the element attributes before the display element (insertBefore or appendChild) or after it.
• For input elements, for IE compatibility, the type attribute is written before the display element (insertBefore or appendChild), and other attributes are written after it.

Instance (compatibility)

The type attribute of <button> created by document. createElement is read-only.

The default value of type is avoided in the test code, because the default value of the <button> type attribute in IE is button, and the default value in other browsers is submit. We recommend that you explicitly declare the type attribute when using it.

Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit ".
 

The Code is as follows: Copy code
// Create input
Var iptEl = document. createElement ('input ');
IptEl. type = 'Password'; // avoid default value
IptEl. name = 'damon ';

Document. body. appendChild (iptEl );

// Create a button
Var btnEl = document. createElement ('click ');
BtnEl. type = 'reset'; // an error is reported in IE.
BtnEl. name = 'damon ';

Document. body. appendChild (btnEl );

Alert (document. getElementsByTagName ('input') [0]. type + ',' +
Document. getElementsByTagName ('button ') [0]. type );


As shown in

Browser <Input> <Button>
IE 6 Yes No
IE 7 Yes No
IE 8 Yes No
IE 9 Yes Yes
Firefox 4.0 Yes Yes
Chrome 13 (DEV) Yes No
Safari 5 Yes No
Opera 11 Yes Yes

The test results show that <input> does not solve this problem.

Solution
MSDN has a description:

As of Microsoft Internet Explorer 5, the type property is read/write-once, but only when an input element is created with the createElement method and before it is added to the document.
That is, only the input element created by document. createElement can be changed once before it is added to the DOM tree. However, this is not the case from the actual situation. This is the only opportunity to set the type at the time of creation. From the test results above, this problem is not fixed until IE9.

For IE, document. createElement (tag), a tag can be a string with an attribute. You can enter the type and name at the time of creation.

Attributes can be encoded with the sTag as long as the entire string is valid HTML.
You can use setAttribute for other modern browsers (such as Chrome and Safari), or use document. createAttribute to create an attribute node and add it to the element node through setAttributeNode.

Method 1:

The Code is as follows: Copy code

Var btnEl;

Try {
BtnEl = document. createElement ('<BUTTON name = damon type = reset> </BUTTON> ');
} Catch (e ){}

If (! BtnEl ){
BtnEl = document. createElement ('click ');

BtnEl. setAttribute ('type', 'reset ');
BtnEl. setAttribute ('name', 'damon ');
}

Document. body. appendChild (btnEl );
Alert (document. getElementsByTagName ('button ') [0]. type +', '+
Document. getElementsByTagName ('button ') [0]. name );

Method 2:

The Code is as follows: Copy code

Var btnEl;

Try {
BtnEl = document. createElement ('<BUTTON name = damon type = reset> </BUTTON> ');
} Catch (e ){}

If (! BtnEl ){
BtnEl = document. createElement ('click ');

Var aType = document. createAttribute ('type ');
Var aName = document. createAttribute ('name ');

AType. value = 'reset ';
AName. value = 'damon ';

BtnEl. setAttributeNode (aType );
BtnEl. setAttributeNode (aName );
}

Document. body. appendChild (btnEl );
Alert (document. getElementsByTagName ('button ') [0]. type +', '+
Document. getElementsByTagName ('button ') [0]. name );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.