How to dynamically create DOM elements in JS

Source: Internet
Author: User

How to dynamically create DOM elements in JS

Recently, due to work needs, you need to click an element to dynamically create a DOM element and display it. Therefore, you have written some relevant JS functions, which are recorded here for your note:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

/*

Function Support for dynamically creating DOM elements

*/

/*

Get the DOM object with an element

@ Obj the ID string of the element

*/

Function getElement (obj)

{

Return typeof obj = 'string '? Document. getElementById (obj): obj;

}

/*

Obtains the position of an element.

@ Obj the DOM object of the element or the ID of the element

*/

Function getObjectPosition (obj)

{

Obj = typeof obj = 'string '? GetElement (obj): obj;

If (! Obj)

{

Return;

}

Var position = '';

If (obj. getBoundingClientRect) // For IEs

{

Position = obj. getBoundingClientRect ();

Return {x: position. left, y: position. top };

}

Else if (document. getBoxObjectFor)

{

Position = document. getBoxObjectFor (obj );

Return {x: position. x, y: position. y };

}

Else

{

Position = {x: obj. offsetLeft, y: obj. offsetTop };

Var parent = obj. offsetParent;

While (parent)

{

Position. x + = obj. offsetLeft;

Position. y + = obj. offsetTop;

Parent = obj. offsetParent;

}

Return position;

}

}

/*

Dynamically bind events to a DOM object

@ OTarget the DOM object bound to the event

@ SEventType: the name of the event to be bound. Note that the on event name is not added, for example, 'click'

@ FnHandler The Bound event handler

*/

Function addEventHandler (oTarget, sEventType, fnHandler)

{

If (oTarget. addEventListener)

{

OTarget. addEventListener (sEventType, fnHandler, false );

}

Else if (oTarget. attachEvent) // for IEs

{

OTarget. attachEvent ("on" + sEventType, fnHandler );

}

Else

{

OTarget ["on" + sEventType] = fnHandler;

}

}

/*

Removes an event from a DOM object.

@ OTarget the DOM object bound to the event

@ SEventType: the name of the event to be bound. Note that the on event name is not added, for example, 'click'

@ FnHandler The Bound event handler

*/

Function removeEventHandler (oTarget, sEventType, fnHandler)

{

If (oTarget. removeEventListener)

{

OTarget. removeEventListener (sEventType, fnHandler, false)

}

Else if (oTarget. detachEvent) // for IEs

{

OTarget. detachEvent (sEventType, fnHandler );

}

Else

{

OTarget ['on' + sEventType] = undefined;

}

}

/*

Create a dynamic DOM object

@ DomParams is the JSON expression of the property of the created object. It has the following attributes:

@ ParentNode the parent element of the created object (it can be an element ID or DOM object)

@ DomId: ID of the created object

@ DomTag: The tag Name of the object to be created. common layout elements such as div span are supported, but special elements such as input and form are not supported.

@ Content the content of the created object

@ OtherAttributes: add other attributes (such as [{attrName: 'style. color', attrValue: 'red'}) to the created object except for the attributes required by the function.

@ EventRegisters add events for the created object, like an array of [{eventType: 'click', eventHandler: adsfasdf }]

-After combination, this parameter has the following form:

{ParentNode: document. body, domTag: 'div ', content:' This is the tested ', otherAttributes: [{attrName: 'style. color ', attrValue: 'red'}], eventRegisters: [{eventType: 'click', eventHandler: fnHandler}]}

*/

Function dynCreateDomObject (domParams)

{

If (getElement (domParams. domId ))

{

ChildNodeAction ('delete', domParams. parentNode, domParams. domId );

}

Var dynObj = document. createElement (domParams. domTag );

With (dynObj)

{

// The id can also be passed in through otherAttributes. However, due to the special nature of the ID

// Input a JSON object and use the dom id attribute as an attachment

Id = domParams. domId;

InnerHTML = domParams. content;

// InnerHTML is a DOM attribute, and id is an element attribute. Pay attention to the difference.

}

/* Add attributes */

If (null! = DomParams. otherAttributes)

{

For (var I = 0; I <domParams. otherAttributes. length; I ++)

{

Var otherAttribute = domParams. otherAttributes [I];

DynObj. setAttribute (otherAttribute. attrName, otherAttribute. attrValue );

}

}

/* Add an attribute at end */

/* Add related events */

If (null! = DomParams. eventRegisters)

{

For (var I = 0; I <domParams. eventRegisters. length; I ++)

{

Var eventRegister = domParams. eventRegisters [I];

AddEventHandler (dynObj, eventRegister. eventType, eventRegister. eventHandler );

}

}

/* Add related events at end */

Try

{

ChildNodeAction ('append', domParams. parentNode, dynObj );

}

Catch ($ e)

{

}

Return dynObj;

}

/*

Delete a child node from the parent node

@ ActionType the default value is append, and the input string is append | remove

@ ParentNode the DOM object of the parent node or the ID of the parent node

@ ChildNode: the DOM object of the deleted child node or the ID of the deleted child node

*/

Function childNodeAction (actionType, parentNode, childNode)

{

If (! ParentNode)

{Return ;}

ParentNode = typeof parentNode = 'string '? GetElement (parentNode): parentNode;

ChildNode = typeof childNode === 'string '? GetElement (childNode): childNode;

If (! ParentNode |! ChildNode)

{Return ;}

Var action = actionType. toLowerCase ();

If (null = actionType | action. length <= 0 | action = 'append ')

{

Action = 'parentnode. appendChild ';

}

Else

{

Action = 'parentnode. removeChild ';

}

 

Try

{

Eval (action) (childNode );

}

Catch ($ e)

{

Alert ($ e. message );

}

}

Example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Var htmlAttributes =

[

{AttrName: 'class', attrValue: 'style name'} // for IEs

,

{AttrName: 'classname', attrValue: 'style name'} // for ff

]

Var domParams = {domTag: 'div ', content: 'innerhtml of dynamic div', otherAttributes: htmlAttributes };

Var newHtmlDom = dynCreateDomObject (domParams );

// Use setAttribute ('style', 'position: absolute .....................')

// The format to specify the style has no effect, only through the following form, jiong

NewHtmlDom. style. zIndex = '20140901 ';

NewHtmlDom. style. position = 'absolute ';

NewHtmlDom. style. left = '100px ';

NewHtmlDom. style. top = '200px ';

I hope this article will help you design javascript programs.

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.