The DOM operation of jquery

Source: Internet
Author: User

Dom (Document Object Model), DOM operations are divided into 3 categories: Dom-core (CORE) Html-dom Css-dom

Dom-core, JS: document.getElementById () document.getElementsByTagName () Document.getelementsbyname (); GetAttribute () SetAttribute ();

Html-core:

Css-core: Gets and sets various properties of the style object element.style.color = "Red";

1. Find the element node:

Find by using the jquery selector: var L = $ ("ul Li:eq (2)"). Text () Gets the textual content of the 3rd Li element in UL

2. To find an attribute node:

After the jquery selector finds the element, it finds the value of its property by attr (). The attr () parameter can be either one, or it can be two. A representation is a query, and 2 representations are assignments.

<div id= "mydiv" title= "Hello">123</div> $ ("#myDiv").  attr ("title"); Hello

3. Create a node:

(1) Create a <li> new element. var l= $ ("<li></li>") to insert this new element into the document: $ ("ul"). Append (l);

var $li 1 = $ ("<span></span>" li element object
var $li 2 = $ ("<span></span > "); The second xhtml rule (closed, lowercase) $ ("). Append ($li 1); Add an element to the element id for mydiv
$ (" #myDiv "<div id= "mydiv" ><span></span> <span></span></div>

$ ("#myDIv"). Append ($li 1). Append ($li 2);//guest: Legendary chained notation, province-by-line code ^_^

Note:(1) dynamically created new element nodes are not automatically added to the document, but instead need to be inserted into the document using other methods.

(2) when creating a single element, pay attention to closing the label and using the standard XHTML format. For example, to create a <p> element, you can use $ ("<p/>") or $ ("<p></p>"), but do not use $ ("<p>") or uppercase $ ("<P/>").
4. Create a text node:

You need to add text content to the element node that you created:

$ ("<li> bananas </li>") $ ("<li> eggplant </li>")

var $li 1 = $ ("<span>first</span>");
var $li 2 = $ ("<span>second</span>");
$ ("#myDIv"). Append ($li 1). Append ($li 2);
Results:<div id= "mydiv"><span>first</span><span>second</span></div >

5. Create an attribute node:

var $li 1 = $ ("<span title="111″>first</span> ");
var $li 2 = $ ("<span title="222″>second</span> ");
$ ("#myDIv"). Append ($li 1). Append ($li 2);
Results:<div id= "mydiv"><span title= "111″>first</span><span title=" 222″>second</span></div>

6. Insert the node:

Append (): Append content to each matching element; <p> Hello!  </p> $ ("P"). Append ("<span> Good Miss You </span>"); Results: <p> Hello! <span> Miss You </span></p>

AppendTo (): Appends the matched element to the specified element, for example: $ (' a '). AppendTo (' B ') is appending A to B $ ("<span> good Want You </span>"). AppendTo ("P"); Results: <p> Hello! <span> Miss you </span></p>

Prepend (): front content to each matched element; <p> Hello!  </p> $ ("P"). Prepend ("<span> Good Miss You </span>"); Results: <p><span> miss you </span> Hello! </p>

Prependto (): All matching elements are pre-placed into the specified element.

After (): Inserts the content after each matching element. <p> Hello!  </p> $ ("P"). After ("<span> good to see you </span>"); Results: <p> Hello! </p><span> Miss you </span>

InsertAfter (): Inserts all matching elements behind the specified element.  $ (' a '). InsertAfter (' B ') appends A to B after $ ("<span> good Want You </span>"). InsertAfter ("P"); Results: <p> Hello! </p><span> Miss You </span>

Before (): Insert content before each matching element

InsertBefore (): Inserts all matching elements to the front of the specified element

$ ("#myDiv"). Append ("<span></span>");// Insert a span element toward an element with ID mydiv
$ ("<span></span>"). AppendTo ("#myDiv");//Upside down, insert the span element into the ID Elements of the mydiv

$ (" #myDiv" <span ></span> "); Go to id for mydiv elements within the first insert span element
$ (" Span lang= "en-US" ><span></span> " #myDiv " span element into the id for mydiv elements in the first

$ (" #myDiv" <span> </span> "); Insert lang= >mydiv "en-us" span "en-us" to id for $ ("<span></span>" # Mydiv "); Upside down, insert span element into id for mydiv after the element (sibling, not child element)

$ ("#myDiv"). Before ("<span></span>");//To insert a SPAN element before an element with ID mydiv (sibling, not child element)
$ ("<span></span>"). InsertBefore ("#myDiv");//Upside down, insert the span element into the ID Mydiv element Front (sibling, not child element)

These methods of inserting nodes can not only insert newly created DOM elements into the document, but also move the original DOM elements.

7. Delete the node:

jquery provides three ways to delete nodes, that is, remove (), detach (), and empty ().

1. The Remove () method removes all matching elements from the DOM,

When a node is removed with the Remove () method, all descendant nodes that the node contains are deleted at the same time. The return value of this method is a reference to the node that has been deleted, so you can use the elements later. The following jquery code illustrates whether an element can continue to be used after it has been removed with the Remove () method.

$ (' ul Li:eq (2) '). Remove (); Get element <ul> Second <li>, delete it from a Web page

var re = $ (' ul Li:eq (2) '). Remove ();  Re.appendto ("ul"); Add the node you just deleted to UL,

Remove () also optionally removes the element $ ("ul Li") by passing parameters. Remove ("li[title= pineapple"); Remove the title of the UL in the Li of pineapple

2. The detach () method, which also removes all matching elements from the DOM, does not remove the matching elements from the jquery object, so that the matching elements can be used in the future. Unlike remove (), all bound events, attached data, and so on are preserved.

3, Empty () method, the empty () method is not to delete the node, but to empty the node, it can empty the elements of all descendant nodes.

8. Replication node:

$ (' ul Li '). Click (function () {

$ (this). Clone (). AppendTo ("ul"); Copy the current node and append to <ul>

})

Clone (True): represents the copying of an element while copying an event bound by a modified element.

9, replace the node:

Select your favorite fruit from the page "<p title=". " > What's your favorite fruit? </p> "Replace" <strong> which fruit do you dislike most? </strong> "

The ReplaceWith () method replaces all matching elements with HTML or DOM elements $ (' P '). ReplaceWith ("<strong> Your least favorite fruit </strong>");

The ReplaceAll () method reverses the operation of the ReplaceWith $ ("<strong> your least favorite fruit </strong>"). ReplaceAll ("P");

Note: If an event has been bound to an element before it is replaced, the previously bound event will disappear with the replaced element, and the event needs to be re-bound on the new element.

10. Parcel node:

Wrapping a node with other tags, jquery provides the appropriate method, wrap (). $ ("<strong>"). Wrap ("<b></b>"); Wrap the strong label with a B tag. <strong> your favorite fruit. </strong>

The result: <b><strong> your favorite fruit. </strong></b>

Warpall () Method: Wrap all the elements with all other tags.  $ ("<strong>"). Wrapall ("<b></b>"); Put multiple strong elements into a <b></b>,

Warpinner () Method: Wraps the child contents of each matching element with other tokens $ ("<strong>"). Wrapinner ("<b></b>"); The result: <strong><b> your favorite fruit. </b></strong>

11. Attribute Operation:

1. Get Properties and Set properties:

$ (' P '); . attr ("title");//Gets the title property of the <p> element $ (' P '). attr ("title", "Your title");    Set a single property; $ (' P '). attr ({"title": "Your title", "Name": "Your Name"}); Set an object in the form of a "name/value" as a property of the matching element

  For example, the attr () method above can set both the value of an element's property and the value of an element's property. There are similar methods such as HTML (), text (), height (), Width (), Val (), and CSS ().

2. Delete the attribute Removeattr () method $ (' P '). Removeattr ("title"); Delete the attributes of the <p> element title;

12. Style Operation:

<p class= "Test" title= "a title" > This is a small test </P>

12, 1 Get style and style:

$ (' P '). attr ("class"); Get the class name of the <p> element;()--test

$ ("P"). attr ("Class", "high"); The style of the settings <p> element is "high", that is, replacing the existing style.

12, 2 Append style

$ ("P"). AddClass ("High"); Add the style "high" to the <p> element;

12, 3 Remove style

$ ("P"). Removeclass ("High");    Remove the style of the <p> element "high"; Removeclass () when it has no parameters, it will delete all the values of class,

12, 4 toggle style, alternating code execution

The toggle () method Here is to alternately execute code ③ and code ④ two functions, hide it if the element was originally displayed, or show it if the element was originally hidden. At this point, the toggle () method mainly controls repetitive switching on behavior.

$ ("togglebtn"). Toggle (function () {//code display element},fucntion () {//code hidden element})

jquery also provides a Toggleclass () method to control the repeated switching of styles.

12, 5 Determine if the style is included

$ ("P"). Hasclass ("High"); Determines whether the <p> element contains the style "high", or returns True if any, otherwise false.

This method is created to enhance the readability of the code. The IS () method is actually called inside jquery to accomplish this function. The method is equivalent to the following code: $ ("P"). Is (". another");

13. Set and get HTML, text, and values:

1. HTML () method: reads or sets the HTML content of an element $ ("P"). html (); Gets the HTML code of the <p> element $ ("P"). HTML ("<strong> What's your favorite fruit?"). </strong> "); Sets the HTML code for the <p> element.

2. Text () Method: This method is similar to the InnerText property in JavaScript, which is used to set or read the text content in an element.

$ ("P"). text (); Gets the text content of the <p> element; $ ("P"). Text ("What's your favorite fruit?"). "); Set the text content of the <p> element as "What's your favorite fruit?" ”

3. Val () Method: The method is similar to the Value property in JavaScript, which is used to get or set the values of an element. Whether the element is a text box, a drop-down list, or a radio box, it can return the value of an element. If the element is multi-select, an array containing all the selected values is returned.

The Val () method can not only set the value of the element, but also the value of the element. In addition, the Val () method has another use, which is to make the options for select (Drop-down list box), checkbox (Marquee), and Radio (radio box) selected, which are often used in form operations.

14. Traverse the node:

1. Children () Method: This method is used to obtain a collection of child elements of a matching element, taking into account only child elements, regardless of any other descendant elements.  

2. Next () method: Used to get the sibling element immediately behind the matching element.

3. Prev () Method: Used to get the sibling element immediately preceding the matching element.

4. Siblings () method: Used to get the sibling element before and after the matching element.

5. Closet () method: used to obtain the nearest matching element

There are many, in the JS packaging set with detailed instructions

15. Css-dom operation

1. CSS () method.

$ ("P"). CSS ("color"); Gets the color property of the P element

$ ("P"). css ({"Color": "Red", "width": "12px"}); Set multiple styles.

$ ("P"). CSS ("color": "Red"); Sets a single style.

(1) If the value is a number, it will be automatically converted to a pixel value.

(2) in the CSS () method, if the attribute has a "-" symbol, such as the font-size and Background-color attributes, if the value of these properties is set without the quotation marks, then it is necessary to use the Camel style notation, for example:

$ ("P"). CSS ({fontSize: "30px", BackgroundColor: "#888888"})

If you enclose the quotation marks, it can be written as "font-size" or "fontSize".

In short, we suggest that you add quotation marks and develop good habits.

$ ("#myDiv"). CSS ("opacity", "0.5″"); Set the transparency of elements with ID mydiv (browser compatible)

$ ("#myDiv"). CSS ("height");//Gets the height of the element with ID mydiv (inPX, browser compatible)
$ ("#myDiv"). Height ();//Ibid. (actual height)

$ ("#myDiv"). CSS ("width");//Get the width of the element with ID mydiv (inPX, browser compatible)
$ ("#myDiv"). width ();//Ibid. (actual width)

2. Offset () method: Gets the relative offset of the current element in the current window, where the returned object consists of two properties, that is, top and left, which are only valid for visible elements.

var offset=$ ("P"). offset ();    var left=offset.left; var top=offset.top;

  var = $ ("#myDiv"). offset ();//Gets the relative offset of the element with ID mydiv in the current window, alert (offset.top + "|" + offset.left);

< Span lang= "en-US" > < Span lang= "en-US" >3. Position () method: Gets the relative offset of the grandparent node that the element is set to position or relative relative to the most recent absolute style property. Also returns the top and left properties.

var offset = $ ("#myDiv"). Position (); Gets the element with ID mydiv relative to the most recent position set to relative or The relative offset of the parent element of the absolute
Alert (offset.top + "|" + offset.left);  

4. ScrollTop () method and ScrollLeft () method: These two methods are the distance from the top of the scroll bar of the element and the distance from the left, respectively.

$ ("#txtArea"). scrolltop (); Gets the distance from the top of the element scroll bar with ID Txtarea
$ ("#txtArea"). ScrollLeft (); get the element with ID txtarea the distance to the left of the scrollbar
$ ("#txtArea"). scrolltop (100);//Set the distance from the top of the element scrollbar with ID Txtarea
$ ("#txtArea"). ScrollLeft (100);//Set the distance from the left side of the element scroll bar with ID txtarea

    

There are also 2 small examples that will be added later

      

     

     

The DOM operation of jquery

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.