On May 21, 10:45 am, kangax <[EMAIL PROTECTED]> wrote:
> Sometimes I hate how in order to make things efficient (?), the code
> size becomes really huge:
>
> var getText = (function(){
> var type = document.createElement('div');
I think a more appropriate name for that variables is "temp" or maybe
just t or x or whatever.
> if (typeof element.textContent != 'undefined') {
I think you meant:
if (typeof type.textContent != 'undefined') {
I don't see the point of a comparison with 'undefined' given that we
know we want a string and only a string (maybe some implementation
decides to return 'object' or 'function' or 'null' or such
weirdness). The above is no better than:
if (type.textContent) {
Some would argue that the strict equals operator (=== ) should be
used. So:
var t = document.createElement('div');
if (typeof t.textContent === 'string') {
> return function(element) {
> return element.textContent;
> }
> }
> else if (typeof element.innerText != 'undefined') {
> return function(element) {
> return element.innerText;
> }
> }
> return function(){};
> })();
Considering the result is more complex code, the benefit of such
optimisation must be weighed against the loss of simplicity.
I expect that before the above becomes noticeably faster the function
will have to be run several thousand times in succession. That is
unlikely to occur so very little (if anything) will be gained by such
optimisation. I'd rather stick with simplicity.
If the intention is to write a more general function, then the above
should be extended to include a recursive function where neither
textContent or innerText are supported, e.g.:
Element.addMethods({
getText: (function() {
var t = document.createElement('div');
if (typeof t.textContent == 'string') {
return function(element) {return element.textContent;}
}
if (typeof t.innerText == 'string') {
return function(element) {return element.innerText;}
}
return function(element) {
return rec(element);
function rec(el) {
var n, x = el.childNodes;
var txt = [];
for (var i=0, len=x.length; i<len; ++i){
n = x[i];
if (3 == n.nodeType) {
txt.push(n.data);
} else if (1 == n.nodeType){
txt.push(rec(n));
}
}
return txt.join('').replace(/\s+/g,' ');
}
}
})()
});
However in the case of Prototype.js, any browser that doesn't support
either textContent or innerText is likely going to have lots of other
issues.
--
Rob
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Spinoffs" group.
To post to this group, send email to rubyonrails-spinoffs@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-spinoffs?hl=en
-~----------~----~----~----~------~----~------~--~---