Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, $('body') can be selecting the body element, but $('body') can be just like $('some text'), so how to distinguish?

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?

like image 736
nonopolarity Avatar asked Jun 21 '10 09:06

nonopolarity


People also ask

What is the difference between $(' header ') HTML () and $(' header ') text ()?

Projects In JavaScript & JQuerytext() – This method sets or returns the text content of elements selected. html() – This method sets or returns the content of elements selected.

How do you select elements in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Which is the correct jQuery selector to select all button elements and input elements with type input?

The :button selector selects button elements, and input elements with type=button.


2 Answers

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>.');
like image 128
Nick Craver Avatar answered Oct 19 '22 05:10

Nick Craver


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").

like image 43
Sean Hogan Avatar answered Oct 19 '22 05:10

Sean Hogan