Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of object shows up in the console as [object Text]?

Say I have the following element:

<p id="thingy">Here is some <em>emphasized</em> text!</p>

In a Javascript console, I'll get its contents with jQuery:

> var theContents = $('<p id="thingy">Here is some <em>emphasized</em> text!</p>').contents();

theContents is now an array that looks like this:

> theContents
["Here is some ", <em>​emphasized​</em>​, " text!"]

So far so good; it seems to be an array, where elements 0 and 2 are strings, and element 1 is a jQuery object. If I output just the first element, it seems to confirm my guess:

> theContents[0]
"Here is some "

However, if I try to concatenate it with another string, I see that I am lacking some understanding:

> 'Hello! ' + contents[0];
"Hello! [object Text]"

So that variable looks like a string, but it is in fact some kind of object. For that matter, the jQuery object in the middle doesn't show up as a regular object, either; it shows up as the raw markup.

Another question references the same problem, but doesn't actually explain it. I've found that I can use contents[0].textContent to solve my real problem, but that still doesn't help me understand exactly what is going on here. Can someone explain to me in detail why all this is behaving the way it is?

like image 575
75th Trombone Avatar asked Apr 02 '12 15:04

75th Trombone


1 Answers

Most jQuery functions return a jQuery object, which for convenience looks and works like an array for most purposes. To quote the documentation, "A jQuery object contains a collection of Document Object Model (DOM) elements" (or "nodes"). So you can assume that each member of the collection is a DOM node, not a string, and accordingly the object you're looking at is a Text node.

In JavaScript when you do string concatenation each operand that isn't a string is automatically converted to one by calling its toString() method. So, just as "1,2,3" is the string representation of the array [1, 2, 3] and "[object HTMLDivElement]" represents a node created with the HTML "<div>", "[object Text]" represents a Text node.

You can read the specification here. Since interface Text inherits from CharacterData it has a data property that contains the string itself. And so:

var theContents = $( '<p id="thingy">Here is some <em>emphasized</em> text!</p>' )
                    .contents();

console.log( theContents[0].data );
// => "Here is some "

console.log( "Hello! " + theContents[0].data );
// => "Hello! Here is some "
like image 58
Jordan Running Avatar answered Nov 20 '22 02:11

Jordan Running