-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.htmlize.js
136 lines (92 loc) · 2.75 KB
/
jquery.htmlize.js
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
/**
* jquery.htmlize
*
* Copyright 2011, Zee Agency http://www.zeeagency.com
* Licensed under the CeCILL-C license
*
* http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html
* http://www.cecill.info/licences/Licence_CeCILL-C_V1-fr.html
*
* @author: Julien Cabanès
* @version: 0.5
*/
(function($) {
// Risky TagNames
var riskyTagNames = ['input', 'textarea', 'select', 'option'],
// Risky Attributes to backup
riskyAttributes = ['value', 'selected', 'checked', 'disabled'],
noValueAttributes = ['selected', 'checked', 'disabled'];
// Prepare cloning
$.fn.htmlizeClone = function(recursive) {
this.each(function() {
var el = this;
if(el.nodeName === 'TEXTAREA') {
el.innerHTML = el.value;
} else if(el.nodeName === 'OPTION') {
if(el.selected) {
el.setAttribute('selected', 'selected');
} else {
el.removeAttribute('selected');
}
} else if(el.children.length) {
// Recursive won't clone
$(el).find('textarea, option').htmlizeClone(true);
}
// Each won't do anything...
});
return recursive ? this : this.clone();
};
// Sync Attributes from Node Properties
$.fn.htmlizeSyncAttributes = function() {
return this.each(function() {
var el = this,
attribute;
for(var i in riskyAttributes) {
if(riskyAttributes.hasOwnProperty(i)) {
attribute = riskyAttributes[i];
// Need to sync : attribute or property is positive
if( attribute in el
&& (el.getAttribute(attribute) !== null || el[attribute])
&& !((el.nodeName === 'TEXTAREA' || el.nodeName === 'SELECT') && attribute === 'value')) {
// Sync attribute from property
if(attribute === 'value') {
el.setAttribute(attribute, el[attribute]);
} else {
if(el[attribute]) {
el.setAttribute(attribute, attribute);
} else {
el.removeAttribute(attribute);
}
}
}
}
}
// Sync Clone's Descendants
if(el.children.length) {
$(el).find(riskyTagNames.join(', ')).htmlizeSyncAttributes();
}
});
};
// returns an outerHTML (by default), concatenates if many elements
$.fn.htmlize = function(options) {
// Configuration
options = $.extend({
innerHTML: false,
clone: true
}, options);
// Clone for footprint & outerHTML
var $el = $(this).htmlizeClone().htmlizeSyncAttributes();
// Serialization
if(options.innerHTML) {
// innerHTML
var result = '';
$el.each(function() {
result += this.innerHTML;
});
return result;
} else {
// outerHTML
return $el.length ? $el.appendTo('<div/>').parent().get(0).innerHTML : '';
}
};
})(jQuery);