Skip to content

Commit e340fd9

Browse files
committed
Simplify parseHtmlFragment
1 parent aa4483c commit e340fd9

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

src/browser.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -208,12 +208,16 @@ var browser = (function (util, proxies, ayepromise, sanedomparsererror, theWindo
208208
};
209209

210210
module.parseHtmlFragment = function (htmlFragment) {
211-
var doc = theWindow.document.implementation.createHTMLDocument(''),
212-
fragmentContainer = doc.createElement('div');
213-
fragmentContainer.innerHTML = htmlFragment;
214-
doc.documentElement.appendChild(fragmentContainer);
211+
var doc = theWindow.document.implementation.createHTMLDocument('');
212+
doc.documentElement.innerHTML = htmlFragment;
213+
214+
var element = doc.querySelector('body').firstChild;
215215

216-
return fragmentContainer.firstChild;
216+
if (!element) {
217+
throw "Invalid source";
218+
}
219+
220+
return element;
217221
};
218222

219223
var addHTMLTagAttributes = function (doc, html) {

test/specs/BrowserSpec.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,19 @@ describe("Browser functions", function () {
206206
});
207207
});
208208

209+
describe("parseHtmlFragment", function () {
210+
it("should parse a single div", function () {
211+
var element = browser.parseHtmlFragment('<div id="the_div"></div>');
212+
213+
expect(element.tagName.toLowerCase()).toEqual('div');
214+
expect(element.id).toEqual('the_div');
215+
});
216+
217+
it("should raise error when parsing an otherwise empty body element", function () {
218+
expect(function () { browser.parseHtmlFragment('<body></body>'); }).toThrow("Invalid source");
219+
});
220+
});
221+
209222
describe("parseHTML", function () {
210223
var oldDOMParser = window.DOMParser;
211224

0 commit comments

Comments
 (0)