跨浏览器解决方案 备忘录

向DOM中注入HTML

1
2
3
4
5
6
7
8
9
// 标准化自封闭标签
const tags = /^(area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
function convert(html){
return html.replace(/^(<(\w+)[^>]*?)\/>/g, (all, front, tag)=>{
console.log(all, front, tag);
return tags.test(tag) ? all : front+"></"+tag+">";
});
}
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
// 提取完整的nodes
function getNodes(htmlString, doc, fragment){
const map = {
"<td":[3,"<table><tbody><tr>","</tr></tbody></table>"],
"<th":[3,"<table><tbody><tr>","</tr></tbody></table>"],
"<tr":[2,"<table><thead>","</thead></table>"],
"<option":[1,"<select multiple>","</select>"],
"<optgroup":[1,"<select multiple>","</select>"],
"<legend":[1,"<fieldset>","</fieldset>"],
"<thead":[1,"<table>","</table>"],
"<tbody":[1,"<table>","</table>"],
"<tfoot":[1,"<table>","</table>"],
"<colgroup":[1,"<table>","</table>"],
"<caption":[1,"<table>","</table>"],
"<col":[2,"<table><tbody></tbody><colgroup>", "</colgroup></table>"],
}
const tagName = htmlString.match(/<\w+/);
let mapEntry = tagName ? map[tagName[0]] :null;
if(!mapEntry){ mapEntry = [0, " "," "]; }
let div = (doc||document).createElement("div");
div.innerHTML = mapEntry[1] + htmlString + mapEntry[2];
while(mapEntry[0]--) div = div.lastChild;
if(fragment) {
while(div.firstChild){
fragment.appendChild(div.firstChild);
}
}
return div.childNodes;
}
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
document.addEventListener("DOMContentLoaded", () => {
function insert(elems, args, callback){
if(elems.length){
const doc = elems[0].ownDocument || elems[0],
fragment = doc.createDocumentFragment(),
script = getNodes(args, doc, fragment),
first = fragment.firstChild;
if(first){
for(let i=0;elem[i];i++){
callback.call(root(elems[i], first),
i > 0 ? fragment.cloneNode(true) ; fragment);
}
}
}
}
const divs = document.querySelectorAll("div");
insert(divs, "<b>Name:</b>", function (fragment) {
this.appendChild(fragment);
});
insert(divs, "<span>First</span> <span>Last</span>",
function (fragment) {
this.parentNode.insertBefore(fragment, this);
});
})