The DOM operation and common functions of jquery

Source: Internet
Author: User

Property manipulation

attr (name) Gets the property value

var imgsrc = $ ("img"). attr ("src")

attr (Name,value) Setting property values

$ ("img"). attr ("src", "images/bg.jpg")

attr (key,function (index)) index is the number of the current element, and the entire function returns a string as the attribute value of the element

$ ("img"). attr ("src", function () {      return  "Images/img0" +math.floor (Math.random () *2-1) + ". jpg";});  Random Pictures

REMOVEATTR (name) Delete attribute value

$ ("img"). Removeattr ("src"); $ ("img"). attr ({src: "test.jpg", alt: "Test Image"}); Sets an object in the form of a "name/value" as a property of all matching elements.

Element Get and set

HTML () Gets the HTML content of the element

HTML (htmlstring) setting elements of HTML content

Text () Gets the textual content of the element

Text (TextString) to set the textual content of the element

Val () Gets the value of the form element

Val (value) sets the value of the form element, and its parameters can also be an array, such as $ (": Radio"). Val (["Radio1", "Radio2"]) indicates that a radio box named Radio1 and Radio2 is selected

Set element style values

. CSS (Name,value) directly sets the element to specify the name of the CSS property

Set multiple CSS properties at the same time

$ ("P"). CSS ({  "color": "White", "Background-color": "#98bf21",  "font-family": "Arial",  "font-size": " 20px ",  " padding ":" 5px "  });

Format with function

$ ("div"). Click (function () {  //increase the width of the div gradually:  $ (this). CSS (    "width", function (index, value) {return parsefloat (value) * 1.2;})  ;

. addclass (Class1class2 ...) Add CSS Category

. Removeclass (Class1class2 ...) Remove CSS Category

. Toggleclass (Class) Toggle CSS Category

var count = 0;$ ("P"). Click (function () {$ (this). Toggleclass ("Highlight", count++% 3 = = 0);});  Add a ' highlight ' class to three clicks per click

$ ("P"). Height (); Gets the altitude value (px) that is currently computed for the first matching element.

$ ("P"). Height (20); Sets the value of the CSS height (hidth) property for each matching element

$ ("P"). width (); Gets the value (px) of the current calculation for the first matching element. $ (window). width (); Gets the width of the current window

$ ("P"). Width (20); Sets the value of the CSS width property for each matching element

Element manipulation

Creating a Node Element

var $div = $ ("<divtitle= ' JQuery ' > Content </div>"); $ ("Dody"). Append ($div);

Internal Insert Node

Internal inserts, which are added inside the element as child nodes of the element.

Append () and Appendto () methods

Append ()--the method is to add the parameters inside the method to the jquery object, such as: A.append (b) means to put B in a, appended to the last position of the child element of A;

AppendTo ()--the method is to add the jquery object to the parameters specified in the AppendTo.

For example: A.appendto (b) means to put A into B, appended to the last position of the child element of B;

Prepend () and Prependto () methods

Prepend ()--the method is to add the parameters inside the method to the jquery object;

For example: A.prepend (b) means putting B in a and inserting it into the first position of the child element of A;

Prependto ()--the method is to add the jquery object to the parameters specified in the prependto.

For example: A.prependto (b) means putting A into B, inserting the first position of the child element of B;

Append (function (index,html))

$ ("div"). Append (returnhtml); functionreturnhtml () {      var str = "<b>write less, domore</b>";};

External Insert Node

The outer insert, i.e., is added outside the element, as the sibling node of the element;

After () and before () methods

After ()--the method is to add the parameters inside the method to the jquery object, such as: A.after (b) means to put B behind A;

Before ()--the method is to add the parameters inside the method to the jquery object. For example: A.before (b) means to put B in front of A;

Methods of InsertAfter () and InsertBefore ()

Logically contrary to the after () and before () methods above

such as: A.insertafter (b); A element will be swapped to the B element;

Replication nodes

$ (selector). Clone ([true]);

With the true parameter, the copied node has an event handler that is bound by the original node.

Replace node

(1) ReplaceAll ()

$ (content). ReplaceAll (selector);

(2) ReplaceWith ()

$ (selector). Repalcewith (content);

Both of these methods are used in the same way, using content instead of selector.

Parcel nodes

(1) Wrap ()

  

$ (selector). Wrap (wrapper); $ (selector). Wrap (function () {...}); $ ("#div2"). Wrap (function () {        return "<b></b>";   });

(2) Unwrap ()

(3) Wrapall ()

$ (selector). Wrapall (wrapper);

(4) Wrapinner ()

$ (selector). Wrapinner (wrapper);

$ (selector). Wrapinner (function () {...});

Summary: Wrap () and Wrapinner () show the same effect, but the former adds a parent node for Seletor, and the latter adds child nodes for selector.

Wrap () and Wrapall () display the same effect, except that each child element in the Seletor is added to the parent node, and the latter adds only one parent to the entire seletor

Delete a node

(1) Remove ()

$ (selector). Remove ([selector])

$ ("div"). Remove ("#div3"); Delete div tags

(2) Detach ()

$ (selector). Detach ([selector])

(3) Empty ()

$ (selector). Empty ()

The return value of the Remove method and the detach method is the jquery node object that was deleted, except that it retains only the object node itself, and other bound events and attached data are removed. The latter are all reserved. The empty method deletes all the child nodes of the specified node, preserving itself.

Traversing the DOM tree

Traverse up

(1) parent ()

Returns the immediate parent element of the selected element.

The method will only traverse the DOM tree up one level.

(2) Parents ()

Returns all the ancestor elements of the selected element, all the way up to the root element of the document (

(3) Parentsuntil ()

Returns all ancestor elements between two given elements.

$ (document). Ready (function () {$ ("span"). Parentsuntil ("div");});  Returns all ancestor elements between <span> and <div> elements


Traverse down

(1) Children ()

Returns all the immediate child elements of the selected element. The method will only traverse the DOM tree down one level.

(2) Find ()

Returns the descendant elements of the selected element, all the way down to the last descendant.

$ (document). Ready (function () {  $ ("div"). Find ("span");});  Returns all <span> elements that belong to <div> descendants

Peer traversal

(1) siblings ()

Returns all the sibling elements of the selected element.

(2) Next ()

Returns the next sibling element of the selected element.

(3) Nextall ()

Returns all the following sibling elements of the selected element.

(4) Nextuntil ()

Returns all the following sibling elements between two given parameters.

(5) Prev (), Prevall () & Prevuntil () method

The prev (), Prevall (), and Prevuntil () methods work in the same way as above, except in the opposite direction: they return the previous sibling element.

Other functions

The Add () method adds an element to the collection of matching elements

The closest () method obtains the first ancestor element of a matching selector, starting at the current element along the DOM tree.

$ (document). Bind ("click", Function (e) {    $ (e.target). Closest ("Li"). Toggleclass ("Hilight");  });// Toggles the yellow background when clicked by the closest list element or its child descendant elements

Each function (Index,element) method prescribes the functions to be run for each matching element

If the array is processed, the first parameter represents the index value, the second parameter represents the array element, and if the JSON object is traversed, it corresponds to the key and value values, and this function can also traverse a set of DOM elements

$ ("button"). Click (function () {  $ ("Li"). each (function () {    alert (the. text ())  });});

<script type= "Text/javascript" > $ (document). Ready (function () {function objinit (obj) {                           return$ (obj). html ("<option> please select </option>");                                              };                                               var OData = {///object notation, key-value pairs are separated by colons, elements are separated by commas, and multiple elements are wrapped in curly braces Producer1: {brand1_1: "model 1_1_1, Model 1_1_2", Brand1_2: "Model 1_2_1, Model 1_2_2"}, Producer2: {brand2_                               1: "Model 2_1_1, Model 2_1_2", brand2_2: "Model 2_2_1, Model 2_2_2"}, Producer3: {brand3_1: "model 3_1_1, Model 3_1_2", Brand3_2: "Model 3_2_1, Model 3_2_2"                    }                                  };                           $.each (Odata,function (key) {$ ("#selA"). Append ("<option>" +key+ "</option>");                    }); $ ("#selA"). ChanGE (function () {Objinit ("#selB");                           Objinit ("#selC");                                         $.each (Odata,function (key1,value1) {if ($ ("#selA option:selected"). Text () = = Key1) { $.each (Value1,function (key2,value2) {$ ("#s                                                ElB "). Append (" <option> "+key2+" </option> ");                                         });                                                $ ("#selB"). Change (function () {Objinit ("#selC"); $.each (Value1,function (key2,value2) {if ($ ("#sel Boption:selected "). Text () = = Key2) {$.each (Value2.split (", "), Function () {$ ("#selC"). Append ("<option>" +this+ "</option>");                                                              });                                                }                                                       });                                         });                           }                                  });                     });                           $ ("#bnt"). Click (function () {var txt = "The vendor you selected:";                           TXT + = $ ("#selAoption: Selected"). Text () + "<br/>";                           TXT + = "Your choice of Brand:";                           TXT + = $ ("#selBoption: Selected"). Text () + "<br/>";                           TXT + = "The model you selected:";                           TXT + = $ ("#selCoption: Selected"). Text () + "<br>";                           $ ("#tips"). HTML (TXT);                                       });      }); </script>

<div class= "Clsinit" >         Manufacturer: <select id= "SelA" ><option> Please select </option></select>         Brand: <select id= "Selb" ><option> Please select </option></select>         model: <select id= "SELC" >< option> Please select </option></select>         <input type= "button" value= "Show" id= "BNT" >    </div> <div class= "Clsinit" id= "Tips" ></div>


Has () reduces the set of matching elements to a subset of descendants that match the specified selector or DOM element

<ul><li>doesthe ul contain an li?</li></ul>


Filter function

(1): EQ (index);

Gets the nth element. The position of this element is calculated from 0.

<p> this isjust a test.</p> <p> so is this</p>

example:$ ("P"). EQ (1);

Result:<p>so is this</p>

(2): Filter (expr)

Filters out the collection of elements that match the specified expression. This method is used to narrow the range of matches. Separate multiple expressions with commas

<p>hello</p><p>helloagain</p><p class= "selected" >and again</p>

Example

$ ("P"). Filter (". selected");

Result

<p class= "selected" >and again</p>

(3): Filter (FN)

Filters out the collection of elements that match the return value of the specified function

<p><ol><li>hello</li></ol></p><p>howare you?</p>

Example

$ ("P"). Filter (function (index) {  return  $ ("ol", this). length = = 0;});

Result: <p>howare you?</p>

(4): Hasclass (Class)

Checks whether the current element contains a particular class, and returns True if any. This is actually the IS ("." + Class).

<div class= "protected" ></div><div></div>

Example: $ ("div"). Hasclass ("protected")

Result:true

(5): Is (expr)

An expression is used to examine the currently selected collection of elements, and returns true if at least one of the elements conforms to the given expression.

<form><inputtype= "checkbox"/></form>

Explam: $ ("Input [type= ' checkbox ']"). Parent (). is ("form")

Result:true;

(6): Not (expr)

To delete an element that matches a specified expression

<p>hello</p><p id= "selected" >hello again</p>

Example

$ ("P"). Not ($ ("#selected") [0])

Result: <p>Hello</p>

(8): Slice (Start,[end])

Select a subset of matches;

<p>Hello</p><p>cruel</p><p>World</p>

Example

$ ("P"). Slice (0,1). Wrapinner ("<b></b>");

Result: <p><b>Hello</b></p>

(9) $ (DOM element). Index (): searches for an element that matches the object represented by the parameter and returns the index value of the corresponding element

(Ten) grep (Array,function (Elementofarray,indexofarray), [invert])

This function is used to filter the array elements, the callback function has two parameters, respectively, to filter the elements of the array and subscript, invert default to False, if true means to get the inverse of the function rule array elements

$.grep (Attr,function (ele,index) {      return ele>5&&indexindex<8;//gets all the elements in the array whose values are greater than 5 and the ordinal is less than 8});

jquery objects and Dom objects are converted to each other

(1) $ (DOM element): Converts one or more DOM elements to a jquery object.

$ (document.body). CSS ("Background", "Black"); Set the page background color

(2) Get (index) method gets the DOM element specified by the selector

$ ("button"). Click (function () {  x=$ ("P"). Get (0);  $ ("div"). Text (X.nodename + ":" + x.innerhtml);});

jquery Object access. EQ Returns a jquery object, only using the JQuery method, and get returns a DOM element object, using only the DOM method.


The DOM operation and common functions 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.