Last active
August 29, 2015 14:05
-
-
Save chemdemo/9c1a8abfdadfaf93dee9 to your computer and use it in GitHub Desktop.
Cross platform way of insertHTML().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {HTMLElement} el | |
* @param {String} where beforeBegin、afterBegin、beforeEnd、afterEnd | |
* @param {String} html | |
*/ | |
function insertHTML(el, where, html) { | |
if (!el) return false; | |
where = where.toLowerCase(); | |
if (el.insertAdjacentHTML) {//IE | |
el.insertAdjacentHTML(where, html); | |
} else { | |
var range = el.ownerDocument.createRange(), | |
frag = null; | |
switch (where) { | |
case 'beforebegin': | |
range.setStartBefore(el); | |
frag = range.createContextualFragment(html); | |
el.parentNode.insertBefore(frag, el); | |
return el.previousSibling; | |
case 'afterbegin': | |
if (el.firstChild) { | |
range.setStartBefore(el.firstChild); | |
frag = range.createContextualFragment(html); | |
el.insertBefore(frag, el.firstChild); | |
} else { | |
el.innerHTML = html; | |
} | |
return el.firstChild; | |
case 'beforeend': | |
if (el.lastChild) { | |
range.setStartAfter(el.lastChild); | |
frag = range.createContextualFragment(html); | |
el.appendChild(frag); | |
} else { | |
el.innerHTML = html; | |
} | |
return el.lastChild; | |
case 'afterend': | |
range.setStartAfter(el); | |
frag = range.createContextualFragment(html); | |
el.parentNode.insertBefore(frag, el.nextSibling); | |
return el.nextSibling; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment