Dissecting JQuery text()
An interesting question came up at work today. We had some existing code that was using the innerText dom method. It worked fine on IE, but not on Firefox (to be clear, I’m used to that working the other way around). If you look at QuirksMode you will see Firefox is the only browser that does not support this method as well.
Turns out if you use innerText on any dom element in IE you will get the text inside the element (in this case a span tag), but in Firefox you just get nothing. I mentioned that JQuery has a text method that does the same thing…but how did that work? I had to look that one up.
Step 1: Find the code
Step 2: Interpreting the code
If you look at the JQuery documentation you will notice there are two methods called text, one that takes a parameter, one that does not. You might assume this is the method that takes the parameter – actually, this single function handles both.
Reading the setter (lines 2 and 3)
On line 3 you see ‘this’ a lot. In this particular case, ‘this’ is a reference to the control you are setting the text of. First the element is being cleared, then an element with the text is being created and appended to the control.
A reference to the controls is being returned when everything is said and done.
Reading the getter (lines 4 – 16)
I’m starting on line 9 with the nodeType code. nodeType 9 is a comment, so that isn’t something we want to change. Also nodeType 1 is an element. You would think we would want the text directly from an element type, but we don’t, we want the ‘text’ nodeType (nodeType 3), which should be a child of an element node. So on line 12 you see a recursive call to the text method. Then, once the appropriate nodeType is found, nodeValue is called.
Line 7 and 8 are just there to loop through the multiple elements that a JQuery selector can return (Note: JQuery Selectors always return an array, even if only one item is returned).
OK, I hope you learned something from this, even if it is that JQuery can be opened up, and you can understand what is going on. Please leave a comment if anything I’ve written is in error.
On a side note, the innerText call that was causing trouble could have been replaced with a call to the JQuery text() method, but they went with innerHtml instead. Also, I did a quick search through JQuery to see if innerText was being used anywhere; it is, once, in a filter function that is part of the selector engine.