views:

61

answers:

4

The reason is that we can do

$('<div>some text</div>').prependTo('#someDiv')

so, this is also ok to do:

$('some text').prependTo('#someDiv')

but we can't change some text to body? body is just as good as any text...

(the above code is adding some text to the div with id someDiv, so what if I want to add the word body to the div?)

but $('body') becomes a selector for the body element... so is there a rule that says, we can use any text as HTML code, so long as it is not the name of HTML elements?

A: 

Dealing with text nodes isn't JQuery's strong suit. You could use normal DOM methods:

$('#someDiv')[0].appendChild(document.createTextNode("body"));
RoToRa
A: 

This is because jQuery considers selectors before creating HTML snippets. "body" is a valid selector and will be used as a selector.

You'd be better of using the prepend function to prepend HTML or text to a node:

 $('#someDiv').prepend('some text');

The value passed to prepend is not used a selector and you could add the text "body".

Mario Menger
+1  A: 

If it contains html tags then it is treated as html (except it strips text before the first tag and after the last). eg $("<div>some text</div>"). Otherwise it is treated as a selector, eg $("some text").

Sean Hogan
+3  A: 

Basically this is never valid:

$('generic text here, *not* a selector or HTML');

That should always be either a selector (finding an element) or html (creating element(s)), you can view the API for $() here.

You want to use one of the other DOM Insertion methods here, .prepend() in this case:

$('#someDiv').prepend('any text or html here is valid, <b>Hey look bold</b>.');
Nick Craver