[jQuery] basic syntax

selector

• $(‘p’)—Accesses all the paragraph elements in the HTML file
• $(‘div’)—Accesses all the div elements in the HTML file
• $(‘#A’)—Accesses all the HTML elements with id=A
• $(‘.b’)—Accesses all the HTML elements with

addClass()
This method is used for applying a CSS class to the selected part of the page.

prepend()
This method inserts the specified content at the beginning of the selected element and returns a jQuery
object. The content can be in the form of text, an HTML element, or a jQuery object.
Let’s insert an h2 element with the text Power of selectors before the paragraph element. The jQuery
code for doing so is as follows:
$(‘p’).prepend(‘<h2> Power of selectors </h2>’);

prependTo()
Similar to prepend(), prependTo() is used for adding DOM nodes dynamically. It inserts the specified
element(s) at the beginning of the selected target, where the target can be in the form of an HTML
element, a string, or a jQuery object. The method returns a jQuery object. The following is the equivalent
of the previous prepend() call.
$(‘<h2> Power of selectors </h2>’).prependTo(‘p’);
We can see that the contents we want to insert (the h2 element) precede the method.

clone()
When we want to add a DOM node (which is a copy of an existing element) on the fly, we use the clone()
method. This method makes a copy of the selected element and returns it as a new jQuery object. To
make a copy of the h2 element in the jQuery code and insert it before the paragraph element, the code
may be as follows:
$(‘h2’).clone().prependTo(‘p’);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s