views:

23

answers:

2

Using jQuery, in Firebug, if the following is done one by one:

foo = $('<div>foo</div>')

foo[0]  // => <div>

foo.html('<span>bar</span>')

foo.html()  // => "<span>bar</span>"

foo[0]  // => <div>

$('body').prepend(foo)  // => shows bar at top of page

it is strange that foo.html() shows the span, but foo[0] shows the div... why is the inconsistency? It seems that foo became a jQuery wrapper for a span element. Shouldn't foo[0] show the span also?

+2  A: 

html() writes/reads the innerHtml property of the <div> element; it doesn't replace the element. What you actually have now is <div><span>bar</span></div>. So no, this isn't particularly strange behavior. :)

Faisal
+1  A: 

The index accessor on a jQuery object accesses the element in the jQuery sequence. In your example, you've created a jQuery sequence with just one element - the div. You can set the contents of that div to be any kind of complex tree, but it's still just one element. html('') sets the inner contents of the node, but the outer node remains unchanged.

Rex M
ah, ok, html() or innerHTML is to replace everything under that node, as in divOne.innerHTML = "<a ...>click me</a>". The `div` is still there. It is just that everything underneath the `div` node is changed. Sometimes easy to forget, especially after a beer.
動靜能量
@Jian Lin: keep drinking and you may be able to reach the Ballmer peak: http://xkcd.com/323/ :)
Faisal