jquery Basic teaching DOM Operations _jquery

Source: Internet
Author: User
Tags prev

For the full name of the DOM, as you all know, DOM is the acronym for Document Object model, which means that it is the documentation objects. Dom is a browser, platform, language-independent interface that uses a DOM interface to easily access all the standard components in a page. Dom operations can generally be divided into three aspects, namely, the DOM core (core), Htm-dom, and Css-dom.

Each page can be represented by a DOM, and each DOM can be viewed as a DOM tree. The following HTML page structure can build a DOM tree, code:

The code is as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
 
 

The constructed Dom tree is as follows:

  

The DOM operations in jquery include: Building "new", adding "add", deleting "delete", changing "modify", checking "Look up" "like Database Operation". The following DOM operation will learn jquerydom operations around the DOM tree above.

 First, check--Find the DOM node

Finding nodes is easy, and using selectors makes it easy to do all kinds of search work. Example: Find element node p returns the text contents within P $ ("P"). Text () Example: Find element node P property returns the property value $ ("P") corresponding to the property name. attr ("title") returns the value of the property title of P.

 Second, build--New DOM node

    1. Create ELEMENT nodes

Creates an element node and adds the node as a child of the <ul> element to the DOM node tree. To create an element point, create an element node to use jquery's Factory function $ () to complete with the following format: $ (HTML), which returns a DOM object based on the passed-in HTML string and wraps the DOM object into a jquery object.

Create an element node jquery code as follows:

$li 1=$ ("<li></li>")

Code return $LI1 is a jquery object packaged by a DOM object. Add the new node to the DOM tree the jquery code is as follows:

 
 

Only the <li> element default "•" is visible in the added page, and because no text is added to the node so that only the default symbol is displayed, the following creates a text node.

The Ps:append () method is to add a DOM node method as described in addition--adding a DOM node.

    2. Create a text node

The factory function using jquery $ () is also able to create text nodes, and the jquery code for creating text nodes is as follows:

$li 2=$ ("<li> apple </li>");

Code return $LI2 is a DOM object wrapped into a jquery object, adding a new text node to the DOM tree with the jquery code as follows:

$ ("ul"). Append ($li 2);

Added after the page can see "Apple", right view page source found that the new text node does not have the title attribute. The following method creates a node with attributes.

    3. Create attribute Node

Create a property node to use a factory function that uses jquery like element nodes and text nodes. The jquery code to create the attribute node is as follows:

$li 3=$ ("<li title= ' durian ' > Durian </li>");
    

Code return $LI3 is also a DOM object wrapped into a jquery object, adding a new attribute node to the DOM tree with the jquery code as follows:

$ ("ul"). Append ($li 3);

Add after the page can see "Durian", the right to view the page source found that the new added attribute node has title= ' Durian ' attribute.

   Third, add--adding DOM nodes

Dynamic new elements are not added to the document without practical meaning, there are several ways to insert the new node into the document, as follows: Append (), Appendto (), prepend (), Prependto (), after (), InsertAfter (), Before (), InsertBefore ().

   1, append () method

The Append () method appends content to the matching element as follows:

$ ("target"). Append (Element);

Cases:

$ ("ul"). Append ("<li title= ' banana ' > Banana </li>");

This method looks for the UL element, then adds the new LI element to the UL.

    2, Appendto () method

The Appendto () method appends all matching elements to the specified element, which is reversed by the append () method [the reverse of the action topic is not an action result] operation. The method is as follows: $ (Element). Appendto (target);

$ ("<li title= ' lychee ' > Litchi <li>"). Appendto ("ul");

This method creates a new element Li and then adds Li to the found UL element.

    3, Prepend () method

The Prepend () method will place each matching element in front of the element to be added, as follows:

$ (target). prepend (Element);

Cases:

$ ("ul"). Prepend ("<li title= ' mango ' > Mango </li>")

The method will look for elements ul and then will be the new LI element as the UL sub node, and as the first child of the UL node inserted into the UL.

    4, Prependto () method

The Prependto () method adds elements to each matching element's internal predecessors, as follows:

$ (Element). Prependto ();

Cases:

$ ("<li title= ' watermelon ' > Watermelon </li>"). Prependto ("ul");

This method inserts the newly created element Li into the found UL element as the first child section element of UL.

   5, after () method

The After () method adds elements after the matching element, and the newly added element is the next sibling element after the target element. The method is as follows:

$ (target). After (element);

Cases:

$ ("P"). After ("<span> new add paragraph new paragraph new add paragraph new paragraph </span>");

Method finds the node p, and then adds the newly created element to the sibling node behind the span node as p.

    6, InsertAfter () method

The InsertAfter () method inserts the newly created element into the sibling of the target element after it has been found. The method is as follows:

$ (Element). InsertAfter (target);

Cases:

$ ("<p>insertafter operation </p>"). InsertAfter ("span");

Method adds the newly created P element to the first sibling node after the target element span, as the target element.

    7, before () method

The Before () method is inserted before each matching element as the previous sibling of the matching element. The method is as follows:

$ (target). before (element);

Cases:

$ ("P"). Before ("<span> below is a paragraph </span>");

The Before method looks for each element p and inserts the new span element into the former sibling of P before the element p.

    8, InsertBefore () method

The InsertBefore () method adds the new element to the target element before it is the first sibling of the target element, as follows:

$ (Element). InsertBefore (target);

Cases:

$ ("<a href= ' > Anchor </a>"). InsertBefore ("ul");

      insertbefore () new A element, the new a element will be added to the element ul before, as a former brother of the UL node.

The first four methods of adding elements are added to the interior of the element, and the last four are actions added to the outside of the element, and these methods can be added to any form of element.

Iv. Deleting--removing DOM node operations

If you want to delete an element in a document jquery provides two ways to delete a node: remove () and empty ();

    1. Remove () method

The Remove () method deletes all matching elements, the passed parameter is used to filter the element, which deletes all the child nodes in the element, and when the matching node and descendants are deleted, the method return value is a reference to the deleted node, so you can use the reference and use the deleted elements.

The method is as follows:

$ (Element). Remove ();

Cases:

$span =$ ("span"). Remove ();

$span. InsertAfter ("ul");

The example of the first deletion of all span elements, the deleted elements used $span receive, the deleted elements added to the UL after the following as the UL brothers node. This action is equivalent to moving all span elements and descendant elements back to ul.

    2, Empty () method.

The empty () method is not strictly a deletion element, it simply empties the node, which clears all the child nodes in the element. The method is as follows:

$ (Element). empty ();

Cases:

$ ("ul li:eq (0)"). empty ();

The example uses the empty method to empty the text value of the first Li in ul. Can only under the LI label default symbol "·".

  Modification--Modifying DOM node operations

There are several ways to modify element nodes in a document: To copy nodes, to replace nodes, to wrap nodes.

    1, copy node $ (element). Clone ()

The replication node method can replicate node elements and can determine whether or not to replicate the behavior of node elements based on parameters. The method is as follows:

$ (Element). Clone (True);

Cases:

$ ("ul li:eq (0)"). Clone (True);

This method copies the first LI element of UL, and the true parameter determines that the element behavior is replicated when the element is copied, and there are no parameters when the behavior is not replicated.

   2. Replace node $ (element). Repalcewith (), $ (Element). Repalceall ()

The replacement node method can replace a node in two forms: ReplaceWith () and ReplaceAll (). Use the ReplaceWith method to replace the preceding element with the following element, and the ReplaceAll method replaces the following element with the preceding element.

The method is as follows:

$ (oldelement). ReplaceWith (newelement); $ (newelement). Repalceall (oldelement);

Cases:

$ ("P"). ReplaceWith ("<strong> I want to leave </strong>");

This method replaces the P element with the strong element.

$ (" 
 

This example replaces all strong elements with the H3 element.

    3, parcel node $ (element). Wrap (), $ (Element). Wrapall (), $ (Element). Wrapinner ()

The Wrapping node method uses other tags to wrap the target element to change the display of the element, and the operation does not break the meaning of the original document. There are three implementation forms of parcel nodes : Wrap (); Wrapall (); Wrapinner ();

The Wrap () method is as follows:

$ (dstelement). Wrap (tag);

Cases:

$ ("P"). Wrap ("<b></b>");

The example method uses the B tag to wrap all the p elements in each element using a B-tag package.

The Wrapall () method is as follows:

$ (dstelement). Wrapall (tag);

Cases:

$ ("P"). Wrapall ("<b></b>");

Visit the example method using the B tag to wrap all the P elements, all the P element tags are wrapped with a B tag.

The Wrapinner () method is as follows:

$ (dstelement). Wrapinner (tag);

Cases:

$ ("strong"). Wrapinner ("<b></b>");

The example uses a B tag to wrap the child elements of each strong element.

Other actions of DOM elements: property manipulation, style manipulation, setting and getting HTML, text and values, traversing node operations, css-dom operations.

   1. Property Operation Attr () and removeattr ()

The attr () method can get element attributes, and can also set element properties. The following method is used when the attr (PARA1) method has an argument to obtain the Para1 property value of the current element when attr (para1,attrvalue) When there are two parameters set the property value of the current element named Para1 is Attrvalue; Example:

 $ ("P"). attr ("title");

This example is used to get the Title property value of the P element.

$ ("P"). attr ("title", "Your favorite fruit");

The example sets the Title property value of the P element to "your favorite fruit";

If you set multiple property values at once, you can use the "name/value" pair to form, for example:

$ ("P"). attr ({"title": "Your favorite Fruit", "name": "Fruit"})

The example sets two property values at a time.

The Removeattr () method deletes a specific property by specifying the property name in the parameter. Cases:

$ ("P"). Removeattr ("name");

The method is to remove the name attribute of the P element.

     2, style Operation AddClass (), Removeclass (), Toggleclass () and Hasclass ()

Add a style addclass () method that uses this method to add the appropriate style to the target element by using the following method:

$ (Element). addclass ();

Cases:

$ ("P"). addclass ("ul");

The example sets the style of element p to ul.

Removes the style removeclass () method, which removes the specified style of the target element by using this method, as follows:

$ (Element). Removeclass ();

Cases:

 $ ("P"). Removeclass ("ul");

The Help to remove the P element of the UL class style.

Toggle the style Toggleclass () method to toggle the style of the target element by using this method, as follows:

$ (Element). Toggleclass ();

Cases:

$ ("P"). Toggleclass ("ul");

The method switches back and forth "add delete implementation Toggle" element P's style ul.

Determines whether the element uses style $ (element). Hasclass (), as follows:

$ (Element). Hasclass (Class);

Cases:

Alert ($ ("P"). Hasclass ("ul"));

Print out whether the P element has a UL style.

      The Ps:addclass () and attr () methods set the different styles, and the attr method sets the attribute value corresponding to the attribute name of the element to the parameter value in the method, AddClass () the property value

Added to the property value corresponding to the property name. Example: An existing element <p class= ' Class1 ' > Element style </p>, and a new style is added using attr () and addclass ().

$ ("P"). attr ("Class", "another").

The result is <p class= ' another ' > element style </>

$ ("P"). AddClass ("Class", "another")

The result is <p class= ' class1 another ' > element style </p>

   3, set up and get HTML "html ()", Text "TextBox" and Value "Val ()"

The HTML () method Gets or sets the HTML element of an element. The method is as follows:

$ (selector). html ();

Cases:

$ ("P"). html (); the example obtains the HTML content of element P.

$ ("P"). HTML ("<strong> Add HTML Content </strong>"); the example sets the HTML content of P to "<strong> Add HTML content </strong>";

     PS: This method can be used for XHTML documents and not for XML documents.

The text () method Gets or sets the literal value of an element. The method is as follows: $ (SELECOTR). text ();

$ ("P"). text (); The example obtains the text text content of element p.

$ ("P"). Text ("Reset text content"); the example sets the text text of element p to "reset text content";

PS: This method applies to both HTML and XML documents.

The Val () method Gets or sets the value of an element, which is returned as an array if the element value is multiple selections, as follows: $ (selector). Val (); Example: text element

<input type= "text" id= "userName" value= "Please enter user name"/>

$ ("#userName"). Val (); Gets the value of the INPUT element.

$ ("#userName"). Val (' Xiangma '); Set the value of the INPUT element to ' Xiangma '.

The Val () method not only operates input, but one of the most important uses is for select Drop-down list box, checkbox "Multiple marquee", Radio "Radio Box".

Example: Multi-selection Assignment application under dropdown box

<select id= "Fruits" multiple= "multiple" ><option> apple </option><option> Banana </option>< Option> Watermelon </option></select>

$ ("#fruits"). Val ([' Apple ', ' banana ']); This example makes both the apples and the bananas selected in the Select.

4, Traversal node operation children (), Next (), Prev (), siblings () and closest ()

The children () method is used to get a set of child elements of a matching element that matches only child elements regardless of any descendant elements. The method is as follows:

$ (selector). Children ();

Cases:

$ ("$ (" body "). Children (). length;

This example obtains the number of child elements of the BODY element;

The next () method is used to match the next sibling node of the element, as follows:

$ (selector). Next ();

Cases:

$ ("P"). Next (). HTML ();

This example obtains the HTML content of the next sibling node of the P element.

The Prev () method is used to match the previous sibling node of the element, as follows:

$ (selector). Prev ();

Cases:

$ ("ul"). Prev (). text ();

This example obtains the textual content of the previous sibling node of the UL element.

The siblings method () is used to match all sibling elements of the target element, as follows:

$ (selector). siblings ();

Cases:

$ ("P"). Slibings (); the example obtains all sibling node elements of the P element.

The closest () method () is used to get the most recent matching element, first checking whether the current element matches if the match is returned directly, otherwise continuing to look up the eligible elements in the parent element and returning the empty jquery object if there are no matching elements.

    5, Css-dom Operation CSS (), offset (), position (), scrolltop () and ScrollLeft ()

The CSS () method is used to get, set one or more attributes of an element. The method is as follows:

$ (selector). CSS ();

Cases:

$ ("P"). CSS ("Color", "red");

The example is used to set the color property of the element to red;

$ ("P"). CSS ("color") The example is used to get the color style value of the element;

$ ("P"). css ({"font-size": "30px", "BackgroundColor", "#888888"});

This example sets multiple styles for an element.

The offset () method gets the offset of the element relative to the current form, and its return object includes two properties: Top and left.

The method is as follows:

$ (selector). Offset ()

The example is used to get the offset of element p.

Ps:offset () is valid only for visible elements.

The position () method gets the relative offset of the ancestor node that the element is set to the nearest position style property to relative or absolute. The method is as follows:

$ (selector). Position ();

Cases:

var postion = $ ("P"). Positon (); var left=positon.left;var top=positon.top;

The example is used to get the position of the element P.

The ScrollTop () and ScrollLeft () methods are used to get the distance from the top of the scroll bar of the element and the distance from the left. The method is as follows:

$ (selector). ScrollTop (); $ (selector). ScrollLeft ();

Cases:

var scrolltop=$ ("P"). scrolltop (); var scrollleft=$ ("P"). ScrollLeft ();

This example is used to get the position of the scroll bar for the element.

You can also add parameters to scroll the element to the specified location. Cases:

$ ("textarea"). ScrollTop (+); $ ("textarea"). ScrollLeft (300);

The above mentioned is the jquery Basic teaching procedure Dom operation, hope to be helpful to everybody.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.