I'm testing behaviour of various browsers dating as far back as 2004. Some don't support the textContent
property of DOM elements. This answer shows an elegant solution which works on IE8, but sadly not on earlier versions of IE, and not on Opera 8.5. Is there an alternative, which doesn't require Object.defineProperty
, and which doesn't use __defineGetter__
, __defineSetter__
as there are also not supported in Opera 8.5.?
At the moment I'm using this ugly workaround:
function setTextContent(el,s) {
if (typeof el.textContent === 'undefined') {
el.innerText = s;
} else {
el.textContent = s;
}
}
and similarly for getting it.
EDIT:
As @LeroyStav suggested document.createTextNode
can be used to set the text content. It doesn't provide an alternative for getting the text content, but if the element into with the newly created text node has no children, innerHTML
would return the same thing. This works in IE7 and Opera 8.5, which are the oldest I've tested:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script charset="utf-8">
window.onload = function () {
var t = document.createTextNode('<'+'script>alert("foo")<'+'/script>');
var cont = document.getElementById('foo'); // set the text content
cont.appendChild(t);
alert(cont.innerHTML); // get the text content (if no children)
}
</script>
</head>
<body>
<div id='foo'></div>
</body>
</html>