html string to dom,javascript - Converting HTML string into DOM elements? - Stack Overflow

小鱼儿 2022-10-06 13:54 141阅读 0赞

Here is a little code that is useful.

var uiHelper = function () {

var htmls = {};

var getHTML = function (url) {

/// Returns HTML in a string format

/// The url to the file with the HTML

if (!htmls[url])

{

var xmlhttp = new XMLHttpRequest();

xmlhttp.open(“GET”, url, false);

xmlhttp.send();

htmls[url] = xmlhttp.responseText;

};

return htmls[url];

};

return {

getHTML: getHTML

};

}();

--Convert the HTML string into a DOM Element

String.prototype.toDomElement = function () {

var wrapper = document.createElement(‘div’);

wrapper.innerHTML = this;

var df= document.createDocumentFragment();

return df.addChilds(wrapper.children);

};

--prototype helper

HTMLElement.prototype.addChilds = function (newChilds) {

/// Add an array of child elements

/// Array of HTMLElements to add to this HTMLElement

///

for (var i = 0; i < newChilds.length; i += 1) { this.appendChild(newChilds[i]); };

return this;

};

--Usage

thatHTML = uiHelper.getHTML(‘/Scripts/elevation/ui/add/html/add.txt’).toDomElement();

发表评论

表情:
评论列表 (有 0 条评论,141人围观)

还没有评论,来说两句吧...

相关阅读