-
June 1st, 2009
Hatin’ on textContent and innerText
It’s surprisingly annoying to get just the text content of an html element in a cross-browser friendly way. I wrote
Element#getTextContent()to take care of this simple operation for me.The Prototype Version:
Element.addMethods({ /** * Element#getTextContent(@element) -> String * Cross-browser means of getting Element#textContent or Element#innerText **/ getTextContent: function(element) { if (!Object.isUndefined(element.textContent)) { return element.textContent; } return element.innerText; } });The Procedural Version
/** * Gets the text content of the specified element. * @param element {HTMLElement} The html element * @return {String} The string content of the specified element. */ function getTextContent(element) { if (typeof element.textContent != "undefined") { return element.textContent; } return element.innerText; }
seb | July 13, 2009 9:39 am
more prototype way :)
getTextContent: function(element) { if (Object.isUndefined(element.textContent)) { return element.innerText; } return element.textContent; }Dan Dean | July 13, 2009 9:45 am
@seb: Good point! I always forget to use those Object methods. I’ll update my implementation.
itska | July 22, 2009 10:52 am
shuffle shuffle whine whine
Dan Dean | August 6, 2009 10:32 pm
@seb: I finally got around to updating this snippet using
Object.isUndefined. Thanks again!Jonah Dempcy | January 5, 2010 11:59 am
MooTools version:
Element.prototype.getText = function() { return $defined(this.textContent) ? this.textContent : this.innerText; };Though in MooTools you can just call get(‘text’) on an element.
Dan Dean | January 5, 2010 12:05 pm
@Jonah: That is nice and short. I think if I wrote this now I’d have started with the ternary format as well. What I don’t like about both of these, though, is the assumption that
innerTextexists…