The DOM operation of the jquery Foundation

Source: Internet
Author: User

The DOM is the abbreviation for the Document Object model, which means that the documents are the objects. Dom is a browser-, platform-, language-agnostic interface that makes it easy to access all the standard components in a page. Dom operations can be divided into three areas: Dom Core (CORE), Htm-dom, and Css-dom.

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

  

View Code

The DOM tree is built as follows:

  

The DOM operations in jquery mainly include: "New", "Add", "delete", "modify", "find" "like Database Operation". The following DOM operations will learn jquerydom operations around the DOM tree above.

First, check--Find DOM node

Finding nodes is easy, and using selectors makes it easy to do a variety of lookups. Example: Find element node p returns the text content within P ("P"). text (); example: Find the attribute of the element node P returns the property value corresponding to the property name of $ ("P"). attr ("title"), which returns the value of P's property title.

Second, build-new DOM node 1, create element node

Create element nodes and add nodes as child nodes of the <ul> element to the DOM node tree. Create an element point, create an element node using JQuery's Factory function $ () to complete the format: $ (HTML), which returns a DOM object based on the incoming HTML string, and wraps the DOM object as a jquery object. Create an element node the jquery code is as follows:

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

The code returns $LI1 is a jquery object wrapped by a DOM object. Add the new node to the DOM tree with the jquery code as follows:

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

You can only see the <li> element default "·" After you add the page, but only the default symbol is displayed because no text is added to the node, and the text node is created below.

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

2. Create a text node

Using the jquery Factory function $ () is also able to create a text node, creating a text node with the jquery code as follows:

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

The code returned $LI2 is a jquery object wrapped by a DOM 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 click on the page source code found the new text node does not have the title attribute. The following method creates a node with attributes.

3. Create attribute Nodes

The Create attribute node is completed using JQuery's factory functions as element nodes and text nodes. The jquery code that creates the attribute node is as follows:

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

The code returned $LI3 is also a jquery object wrapped by a DOM object, adding the new attribute node to the DOM tree in the jquery code as follows:

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

Added after the page can see "• Durian", right-click on the page to see the source of the newly added attribute node has title= ' Durian ' attribute.

Three, increase--add DOM node

Dynamic new elements are not added to the document, and there are several ways to insert the newly created 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, by doing the following: $ ("target"). Append (Element);

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

This method finds the UL element and then adds the newly created 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 inverse of the action topic is not an action result] operation. The method is as follows: $ (Element). AppendTo (target);

$ ("<li title= ' lychee ' > Lychee <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 adds the elements to be added within each matched element, by the following method: $ (target). prepend (Element);

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

This method finds the element UL and then adds the newly created Li element as the UL child node and inserts it into the UL as the first child node of UL.

4. Prependto () method

The Prependto () method adds an element to the inside of each matched element by the preceding method, as follows: $ (Element). Prependto ();

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

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

5. After () method

The After () method adds an element after the matched element, and the newly added element is the immediate sibling element after the target element. Here's how: $ (target). After (element);

$ ("P"). After ("<span> new addition to paragraph new addition to paragraph of new paragraph </span>");

The method will find node p and then add the newly created element to the span node as the sibling node of P.

6. InsertAfter () method

The InsertAfter () method inserts the newly created element into the sibling node of the target element after the target element is found. The method is as follows: $ (Element). InsertAfter (target);

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

The Add method adds the newly created P element to the first sibling node behind the target element, after finding the target element span.

7. Before () method

The Before () method is inserted before each matched element, making it the previous sibling node that matches the element. Here's how: $ (target). before (element);

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

The Before method finds each element p, inserting the newly created span element into element p as the previous sibling node of P.

8. InsertBefore () method

The InsertBefore () method adds a new element to the target element before it is used as the previous sibling node of the target element, as follows: $ (Element). InsertBefore (target);

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

InsertBefore () Creates a new a element, adds the newly created a element to the element ul, as the previous sibling node of UL.

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

Iv. Delete--Remove DOM node operation

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 removes all matching elements, and the passed parameters are used to filter the elements, which can delete all child nodes in the element, and when the matching nodes and descendants are deleted, the method return value is a reference to the deleted node, so you can use the reference and then use the deleted element. The method is as follows: $ (Element). Remove ();

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

$span. InsertAfter ("ul");

In this example, all the span elements are removed, the deleted elements are received using $span, and the deleted elements are added to UL's sibling nodes. This action is equivalent to moving all the span elements and descendant elements behind the UL.

2, Empty () method.

The empty () method strictly does not delete the element, which simply empties the node, which empties all the child nodes in the element. The method is as follows: $ (Element). empty (); Example:

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

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

Five, change--Modify DOM node operation

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

1. Copy node $ (element). Clone ()

The Copy node method replicates the node elements and is able to determine whether to copy the behavior of the node elements according to the parameters. The method is as follows: $ (Element). Clone (True);

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

The method copies the first LI element of UL, and the true parameter determines that the element behavior is copied when the element is copied, without parameters when the behavior is not copied.

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 subsequent element with the preceding element. The methods are as follows: $ (oldelement). ReplaceWith (newelement); $ (newelement). Repalceall (oldelement); Example: $ ("P"). ReplaceWith ("<str Ong> I want to leave </strong> "); This method replaces the P element with the strong element.

$ ("

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

The Wrap node method wraps the target element with other tags to change the display of the element, and the operation does not break the original document's meaning. The wrapping node has three kinds of realization forms: Wrap (); Wrapall (); Wrapinner ();

The Wrap () method is as follows: $ (dstelement). Wrap (tag), for example:

$ ("P"). Wrap ("<b></b>"); This example method wraps all p elements with a B tag and each element uses a B label package.

The Wrapall () method is as follows: $ (dstelement). Wrapall (tag);

$ ("P"). Wrapall ("<b></b>"); The sample method uses the B tag to wrap all p elements, and all P element labels are wrapped with a B tag.

The Wrapinner () method is as follows: $ (dstelement). Wrapinner (tag);

$ ("strong"). Wrapinner ("<b></b>"); the example uses the B tag to wrap the child elements of each strong element.

Other actions for DOM elements: property manipulation, style manipulation, setting and getting HTML, text and values, traversing node operations, css-dom operations. 1. Attribute Operation attr () and removeattr ()

The attr () method can acquire element attributes and can also set element properties. The method is as follows, when the attr (Para1) method has a parameter to obtain the property value of the current element's para1, when the attr (Para1,attrvalue) has two parameters, the property named Para1 of the current element is set to the value of attrValue;

$ ("P"). attr ("title"); This example is used to get the value of the P element's title property.

$ ("P"). attr ("title", "Your favorite Fruit"); the example sets the P element's Title property value to "your favorite fruit";

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

$ ("P"). attr ({"title": "Your favorite Fruit", "name": "Fruit"}). The example sets two property values at a time.

The Removeattr () method is used to delete a specific property by specifying the property name in the parameter. Cases:

$ ("P"). Removeattr ("name"); The method is to remove the P element's Name property.

2. Style Operation AddClass (), Removeclass (), Toggleclass (), and Hasclass ()

Add the Style addclass () method, using this method to add the appropriate style to the target element, as follows: $ (Element). addclass ();

$ ("P"). addclass ("ul"); the example sets the style of the element p to ul.

Remove the style Removeclass () method, which removes the specified style from the target element by using the method as follows: $ (Element). Removeclass ();

$ ("P"). Removeclass ("ul"); it's time to help get rid of the UL class style of P elements.

Toggle the style Toggleclass () method, which toggles the style of the target element by using the method as follows: $ (Element). Toggleclass ();

$ ("P"). Toggleclass ("ul"); This method toggles the "Add Delete implementation Toggle" element P's style UL back and forth.

Determines whether the element uses the style $ (element). Hasclass (), the method is as follows: $ (Element). Hasclass (Class);

Alert ("P"). Hasclass ("ul")); print out whether the P element has a UL style.

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

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

$ ("P"). attr ("Class", "another"). The result is <p class= ' another ' > element style </>

$ ("P"). AddClass ("Class", "another") result is <p class= ' class1 another ' > element style </p>

3. Set and get HTML "html ()", text "text ()" and Value "Val ()"

The HTML () method Gets or sets the HTML element for an element. Here's how: $ (selector). HTML (); Example:

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

$ ("P"). HTML ("<strong> Add HTML Content </strong>"); This 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. Here's how: $ (SELECOTR). text (); Example:

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

$ ("P"). Text ("Reset text content"); This example sets the text text of the element p to "re-set textual content";

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

The Val () method Gets or sets the value of an element, and returns as an array if the element value is multi-selected, 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 '); Sets the value of the INPUT element to ' Xiangma '.

The Val () method can not only manipulate input, but one of the most important uses for select "Drop-down list box", checkbox "marquee", Radio "Radio Box". Example: Multi-select assignment 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 the select Apple and banana two items selected.

4. Traverse node Operation Children (), Next (), Prev (), siblings (), and closest ()

The children () method is used to get a collection of child elements that match elements, and only matching child elements does not take into account any descendant elements. Here's how: $ (selector). Children (); Example:

$ ("$ (" body "). Children (). Length; The 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 (); Example:

$ ("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 an element by the following method: $ (selector). Prev ();

$ ("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 ();

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

The closest () method () is used to obtain the most recent matching element, first checking whether the current element matches if the match is returned directly, otherwise continuing to find the eligible element in the parent element returned, and returning an 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 properties of an element. Here's how: $ (selector). CSS (); Example:

$ ("P"). CSS ("Color", "red"); the example is used to set the element's Color property to red;

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

$ ("P"). css ({"font-size": "30px", "BackgroundColor", "#888888"}); This example sets multiple styles for an element.

The offset () method is used to get the offset of an element relative to the current form, and its returned object includes two properties: Top and left. Here's how: $ (selector). Offset ()

var offset= $ ("P"). offset (); var Left=offset.left;var top=offset.top; This example is used to get the offset of the element p.

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

The position () method is used to get the relative offset of an element in the nearest position style property set to relative or absolute's ancestor node. Here's how: $ (selector). position (); Example:

var postion = $ ("P"). Positon (); var left=positon.left;var top=positon.top; This example is used to get the position of the element P.

The ScrollTop () and ScrollLeft () methods are used to get the distance of the element's scroll bar from the top and the distance from the left. The methods are as follows: $ (selector). ScrollTop (); $ (selector). ScrollLeft ();

var scrolltop=$ ("P"). scrolltop (); var scrollleft=$ ("P"). ScrollLeft (); the example is used to get the position of the element's scroll bar.

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

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

The DOM operation of the jquery Foundation

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.