Skip to content

Commit

Permalink
Merge pull request #275 from DrRataplan/master
Browse files Browse the repository at this point in the history
Rewrite pretty-printing HTML elements to prevent throwing internal errors
  • Loading branch information
logicalparadox committed Aug 9, 2014
2 parents ab999d8 + 4b31574 commit 6c789b1
Showing 1 changed file with 30 additions and 20 deletions.
50 changes: 30 additions & 20 deletions lib/chai/utils/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,6 @@ function inspect(obj, showHidden, depth, colors) {
return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth));
}

// https://gist.github.com/1044128/
var getOuterHTML = function(element) {
if ('outerHTML' in element) return element.outerHTML;
var ns = "http://www.w3.org/1999/xhtml";
var container = document.createElementNS(ns, '_');
var elemProto = (window.HTMLElement || window.Element).prototype;
var xmlSerializer = new XMLSerializer();
var html;
if (document.xmlVersion) {
return xmlSerializer.serializeToString(element);
} else {
container.appendChild(element.cloneNode(false));
html = container.innerHTML.replace('><', '>' + element.innerHTML + '<');
container.innerHTML = '';
return html;
}
};

// Returns true if object is a DOM element.
var isDOMElement = function (object) {
if (typeof HTMLElement === 'object') {
Expand Down Expand Up @@ -78,9 +60,37 @@ function formatValue(ctx, value, recurseTimes) {
return primitive;
}

// If it's DOM elem, get outer HTML.
// If this is a DOM element, try to get the outer HTML.
if (isDOMElement(value)) {
return getOuterHTML(value);
if ('outerHTML' in value) {
return value.outerHTML;
// This value does not have an outerHTML attribute,
// it could still be an XML element
} else {
// Attempt to serialize it
try {
if (document.xmlVersion) {
var xmlSerializer = new XMLSerializer();
return xmlSerializer.serializeToString(value);
} else {
// Firefox 11- do not support outerHTML
// It does, however, support innerHTML
// Use the following to render the element
var ns = "http://www.w3.org/1999/xhtml";
var container = document.createElementNS(ns, '_');

container.appendChild(value.cloneNode(false));
html = container.innerHTML
.replace('><', '>' + value.innerHTML + '<');
container.innerHTML = '';
return html;
}
} catch (err) {
// This could be a non-native DOM implementation,
// continue with the normal flow:
// printing the element as if it is an object.
}
}
}

// Look up the keys of the object.
Expand Down

0 comments on commit 6c789b1

Please sign in to comment.