Say I have the following element:
<p id="thingy">Here is some <em>emphasized</em> text!</p>
> 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
2 are strings, and element
1 is a jQuery object. If I output just the first element, it seems to confirm my guess:
> theContents "Here is some "
However, if I try to concatenate it with another string, I see that I am lacking some understanding:
> 'Hello! ' + contents; "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.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?
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.
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 "
[object Text]" represents a Text node.
var theContents = $( '<p id="thingy">Here is some <em>emphasized</em> text!</p>' ) .contents(); console.log( theContents.data ); // => "Here is some " console.log( "Hello! " + theContents.data ); // => "Hello! Here is some "