Jquery-based DOM operations
Dom is short for Document Object Model, which means Document Object Model. DOM is an interface unrelated to browsers, platforms, and languages. You can use this interface to easily access all the standard components on the page. DOM operations can be divided into three aspects: DOM Core (Core), HTM-DOM and CSS-DOM.
Every webpage can be represented by DOM, and every DOM can be regarded as a DOM tree. The following html page structure can be used to construct a DOM tree. Code:
View Code
The constructed DOM tree is as follows:
DOM operations in JQuery mainly include: Create, add, delete, modify, and search for database operations ]. The following DOM Operations perform the JQueryDOM learning operation on the preceding DOM tree.
I. Search for DOM nodes
It is very easy to find nodes. You can easily complete various search tasks by using selector. For example, find the Element Node p and return the text content in p $ ("p "). text (); example: Find the attribute of Element Node p and return the attribute value corresponding to the attribute name $ ("p "). attr ("title"), returns the value of the property title of p.
2. Create-create a DOM Node 1. Create an element node
Create an element node and add the node as a child node of the <ul> element to the DOM node tree. First, create an element point. Create an element node using Jquery's factory function $ (). The format is as follows: $ (html). This method returns a DOM object based on the input html string, and wrap the DOM object into a JQuery object and return it. The JQuery code for creating an element node is as follows:
$ Li1 = $ ("<li> </li> ")
$ Li1 is a JQuery object encapsulated by a DOM object. The JQuery code for adding a new node to the DOM tree is as follows:
$ ("Ul"). append ($ li1 );
The default <li> element "·" can only be seen on the page after the addition. Because no text is added to the node, only the default symbol is displayed. The text node is created below.
PS: The append () method is to add a DOM node. For details, see add-Add a DOM node.
2. Create a text node
Use the JQuery factory function $ () to create a text node. The JQuery code for creating a text node is as follows:
$ Li2 = $ ("<li> Apple </li> ");
The Code returns $ li2, which is a JQuery object encapsulated by the DOM object. Add the new text node to the DOM tree. The JQuery code is as follows:
$ ("Ul"). append ($ li2 );
After adding the node, You can see "· Apple" on the page. Right-click to view the page source code and find that the newly added text node has no title attribute. The following method creates a node with attributes.
3. Create an attribute node
You can use the JQuery factory function to create an attribute node like an element node or a text node. The JQuery code for creating an attribute node is as follows:
$ Li3 = $ ("<li title = 'durian'> durian </li> ");
The Code returns $ li3, which is also a JQuery object encapsulated by the DOM object. Add the newly created attribute node to the DOM tree. The JQuery code is as follows:
$ ("Ul"). append ($ li3 );
After adding the node, You can see "· durian" on the page. Right-click to view the source code of the page and find that the newly added property node has the title = 'durian' attribute.
3. Add-add DOM nodes
It does not make sense to add the dynamic creation element to the document. There are multiple methods to insert the newly created node into the document: append (), appendTo (), prepend (), prependTo (), after (), insertAfter (), before (), insertBefore ().
1. append () method
The append () method adds content to the matching element as follows: $ ("target"). append (element); example:
$ ("Ul"). append ("<li title = 'bananas '> bananas </li> ");
This method finds the ul element and then adds the newly created li element to ul.
2. appendTo () method
The appendTo () method appends all matching elements to the specified element. This method is the inverse of the append () method [the inverse of the subject is not the result of the operation. The method is as follows: $ (element). appendTo (target); example:
$ ("<Li title = 'lychee '> lychee <li>"). appendTo ("ul ");
This method creates a new element li and adds li to the searched ul element.
3. prepend () method
The prepend () method preends the element to be added to each matching element. The method is as follows: $ (target). prepend (element); example:
$ ("Ul"). prepend ("<li title = 'mango '> mango </li> ")
This method searches for the element ul and then inserts the newly created li element into ul as the ul sub-node and as the first sub-node of ul.
4. prependTo () method
The prependTo () method adds an element to the front of each matching element. The method is as follows: $ (element). prependTo (); example:
$ ("<Li title = 'watermelon '> watermelon </li>"). prependTo ("ul ");
This method inserts the newly created element li into the searched ul element as the first child element of ul.
5. after () method
The after () method adds an element to the matched element, and the newly added element serves as the adjacent sibling element after the target element. The method is as follows: $ (target). after (element); example:
$ ("P"). after ("<span> new addition Section new addition section </span> ");
The method searches for node p, and adds the newly created element to the end of the span node as the p sibling node.
6. insertAfter () method
The insertAfter () method inserts the new element into the target element to act as the sibling node of the target element. The method is as follows: $ (element). insertAfter (target); example:
$ ("<P> insertAfter operation </p>"). insertAfter ("span ");
Method to add the newly created p element to the end of the target element span as the first sibling node after the target element.
7. before () method
The before () method is inserted before each matching element as the first sibling node of the matching element. The method is as follows: $ (target). before (element); example:
$ ("P"). before ("<span> the following section </span> ");
The before method searches for each element p and inserts the newly created span element into element p as the previous sibling node of p.
8. insertBefore () method
The insertBefore () method adds the new element to the target element as the first sibling node of the target element. The method is as follows: $ (element). insertBefore (target); example:
$ ("<A href = '#'> anchor </a>"). insertBefore ("ul ");
InsertBefore () creates Element a and adds the new element a to element ul as the former brother node of ul.
The first four methods for adding an element are added to the element, and the last four are operations for adding an element to the element. These methods can complete element addition in any form.
4. Delete-delete DOM nodes
If you want to delete an element in the document, JQuery provides two methods to delete nodes: remove () and empty ();
1. remove () method
The remove () method deletes all matched elements. The input parameters are used to filter elements. This method can delete all child nodes in the element. When the matched nodes and their descendants are deleted, the return value of this method is a reference to the deleted node. Therefore, you can use this reference before using these deleted elements. The method is as follows: $ (element). remove (); example:
$ Span = $ ("span"). remove ();
$ Span. insertAfter ("ul ");
In this example, delete all span elements, use $ span to receive the deleted elements, and add the deleted elements to ul as ul's sibling nodes. This operation is equivalent to moving all span elements and descendant elements behind ul.
2. empty () method.
Strictly speaking, the empty () method does not delete elements. Instead, it only clears nodes and can clear all child nodes in the elements. The method is as follows: $ (element). empty (); example:
$ ("Ul li: eq (0)"). empty ();
This example uses the empty method to clear the text value of the first li in ul. Only the default symbol "·" of the li label can be entered.
V. Modify-Modify DOM node operations
You can modify the element nodes in the document by copying nodes, replacing nodes, and wrapping nodes.
1. Copy node $ (element). clone ()
The copy node method can copy node elements and determine whether to copy node elements based on parameters. The method is as follows: $ (element). clone (true); example:
$ ("Ul li: eq (0)"). clone (true );
This method copies the first li element of ul. The true parameter determines that the element behavior is also copied when the element is copied. If the behavior is not copied, there is no parameter.
2. Replace node $ (element). repalcewith (), $ (element). repalceAll ()
The node replacement method can replace a node in two forms: replaceWith () and replaceAll (). replaceWith is used to replace the previous element with the subsequent element. replaceAll is used to replace the following element with the previous element. The method is as follows: $ (oldelement ). replaceWith (newelement); $ (newelement ). repalceAll (oldelement); example: $ ("p "). replaceWith ("<strong> I want to leave </strong>"); this method replaces the p element with the strong element.
$ ("<H3> replace strong 3. Package nodes $ (element). wrap (), $ (element). wrapAll (), $ (element). wrapInner ()
The wrap node method uses other labels to wrap the target element to change the display form of the element, and this operation does not damage the meaning of the original document. Three methods are available for the package node: wrap (); wrapAll (); wrapInner ();
The wrap () method is as follows: $ (dstelement). wrap (tag); example:
$ ("P"). wrap ("<B> </B>"); this example uses the B label to wrap all the p elements and each element uses the B label.
The wrapAll () method is as follows: $ (dstelement). wrapAll (tag); example:
$ ("P "). wrapAll ("<B> </B>"); the access example uses the B label to wrap all p elements, and all p element labels are wrapped with a B label.
The wrapInner () method is as follows: $ (dstelement). wrapInner (tag); example:
$ ("Strong"). wrapInner ("<B> </B>"); this example uses the B tag to enclose the child elements of each strong element.
Other operations of Dom elements: attribute operations, style operations, setting and obtaining HTML, text and values, traversing node operations, and Css-Dom operations. 1. Attribute operations attr () and removeAttr ()
The attr () method can obtain element attributes and set element attributes. The method is as follows. When the attr (para1) method has a parameter, it is used to obtain the para1 attribute value of the current element. When attr (para1, attrValue) when there are two parameters, set the attribute value of the current element to "attrValue". For example:
$ ("P"). attr ("title"); this example is used to obtain the title attribute value of the p element.
$ ("P"). attr ("title", "your favorite fruit"); in this example, set the title attribute value of the p element to "your favorite fruit ";
If you set multiple attribute values at a time, you can use the name/value pair format, for example:
$ ("P"). attr ({"title": "your favorite fruit", "name": "Fruit "}). This example sets two attribute values at a time.
The removeAttr () method is used to delete a specific attribute by specifying the attribute name in the parameter. Example:
$ ("P"). removeAttr ("name"); this method is used to remove the name attribute of the p element.
2. style operations addClass (), removeClass (), toggleClass (), and hasClass ()
Add the style addClass () method. Use this method to add the corresponding style to the target element. The method is as follows: $ (element). addClass (); example:
$ ("P"). addClass ("ul"); this example sets the style of element p to ul.
Remove style removeClass (). Use this method to remove the specified style of the target element. The method is as follows: $ (element). removeClass (); example:
$ ("P"). removeClass ("ul"); remove the ul style of the p element.
Switch the style toggleClass () method. Use this method to switch the style of the target element. The method is as follows: $ (element). toggleClass (); example:
$ ("P"). toggleClass ("ul"); this method switches back and forth [add Delete implement switch] The style ul of element p.
Determine whether the element uses the style $ (element). hasClass (). The method is as follows: $ (element). hasClass (class); example:
Alert ($ ("p"). hasClass ("ul"); prints whether the p element has a ul style.
PS: The addClass () and attr () methods have different styles. the attr method sets the attribute value corresponding to the attribute name of an element to the parameter value in the method, and addClass () sets the attribute value.
Add to the property value corresponding to the property name. For example, an existing <p class = 'class1'> element style </p> is used to add a new style by using attr () and addClass.
$ ("P"). attr ("class", "another"). The result is <p class = 'another '> element style </>
$ ("P"). addClass ("class", "another") returns <p class = 'class1 another '> element style </p>
3. Set and obtain HTML [html ()], text [text ()], and value [val ()]
The html () method gets or sets the html element of an element. The method is as follows: Optional (selector).html (); example:
$ ("P" ).html (); this example obtains the html content of element p.
$ ("P" ).html ("<strong> Add html content </strong> "); in this example, set the html content of p to <strong> Add html content </strong>.
PS: This method can be used for XHTML documents and cannot be used for XML documents.
The text () method gets or sets the text value of an element. The method is as follows: $ (selecotr). text (); example:
$ ("P"). text (); this example obtains the text content of element p.
$ ("P"). text ("Reset text content"); this example sets the text of element p to "Reset text content ";
PS: This method applies to both html and XML documents.
The val () method is used to obtain or set the value of an element. If multiple values are selected, the value is returned as an array. The method is as follows: $ (selector). val (); example: text element
<Input type = "text" id = "userName" value = "Enter the user name"/>
$ ("# UserName"). val (); obtain the value of the input element.
$ ("# UserName"). val ('xiangma'); set the value of the input element to 'xiangma '.
The val () method can operate not only input, but also select [drop-down list box], checkbox [multiple selection box], and radio [single choice ]. Example: <select id = "fruits" multiple = "multiple"> <option> Apple </option> <option> banana </option> <option> Watermelon </option> </select>
$ ("# Fruits"). val (['apple', 'Banana ']); this example selects the apple and banana items in the select statement.
4. Traverse nodes for children (), next (), prev (), siblings (), and closest ()
The children () method is used to obtain the child element set of the matching element. Only child elements are matched without any descendant elements. The method is as follows: $ (selector). children (); example:
$ ("$ (" 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 an element. The method is 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. The method is as follows: $ (selector). prev (); example:
$ ("Ul"). prev (). text (); this example obtains the text content of the last sibling node of the ul element.
The siblings method () is used to match all the sibling elements of the target element. The method is as follows: $ (selector). siblings (); example:
$ ("P"). slibings (); The example obtains all the sibling node elements of the p element.
The closest () method () is used to obtain the most recent Matching Element. First, check whether the current element matches. If it matches, the system returns the result directly. Otherwise, the system continues to search for the element that matches the condition in the parent element and returns the result, if no matching element exists, an empty JQuery object is returned.
5. CSS-Dom operations: css (), offset (), position (), scrollTop (), and scrollLeft ()
The css () method is used to obtain and set one or more attributes of an element. The method is as follows: Optional (selector).css (); example:
$ ("P" ).css ("color", "red"); this example is used to set the color attribute of an element to red;
$ ("P" ).css ("color") This example is used to obtain the color Style value of an element;
$ ("P" ).css ({"font-size": "30px", "backgroundColor", "#888888"}); this example is used to set multiple styles of an element.
The offset () method is used to obtain the offset of an element relative to the current form. The returned object includes two attributes: top and left. The method is as follows: $ (selector). offset ()
Var offset = $ ("p"). offset (); var left = offset. left; var top = offset. top; this example is used to obtain the offset of element p.
PS: offset () is only valid for visible elements.
The position () method is used to obtain the relative offset of the last position style attribute of an element set to relative or absolute. The method is as follows: $ (selector). position (); example:
Var postion = $ ("p"). positon (); var left = positon. left; var top = positon. top; this example is used to obtain the position of element p.
The scrollTop () and scrollLeft () methods are used to obtain the distance between the scroll bar of an element from the top and the left. The method is as follows: $ (selector). scrollTop (); $ (selector). scrollLeft (); example:
Var scrollTop = $ ("p"). scrollTop (); var scrollLeft = $ ("p"). scrollLeft (); this example is used to obtain the position of the element's scroll bar.
You can also add a parameter to scroll the element to the specified position. Example:
$ ("Textarea"). scrollTop (300); $ ("textarea"). scrollLeft (300 );