JQuery DOM Operations Summary Tutorial

Source: Internet
Author: User
Tags comments hash

page Load Domready event





The so-called Domready, the document is ready, we all know that in the operation of the DOM must be done after the DOM tree is finished loading. How to detect that the DOM tree has been built, here are some ways to implement it:





1. Use jquery:





With JQuery


$ (document). Ready (function () {/* ... */});


Shorter jQuery version


$ (function () {/* ... */});





2. Listening for domcontentloaded events, the DOM tree is created and is triggered, and IE10 the following version is not supported.





Without jQuery (doesn ' t work in older IEs)


Document.addeventlistener (' domcontentloaded ', function () {


Your code goes here


}, False);





3. Monitor readystate State, can realize cross-browser





ReadyState Status Properties:





"Uninitialized"? Original state


"Loading"? In the download data


"Loaded"? Download complete


"Interactive"? Not finished yet


"Complete"? Script Execution Complete





R (function () {


Alert (' DOM ready! ');


});


function r (f) {/in/.test (document.readystate)? SetTimeout (' R (' +f+ ') ', 9): F ()}





This method is to continuously monitor the loading state of the readystate, and then execute the corresponding method after the loading is complete. Specific can refer to: http://www.dustindiaz.com/smallest-domready-ever





code that corresponds to the execution of a particular page





If all of the page's code is written in a JavaScript file, such code will be difficult to maintain. The easy way to do this is to execute different code based on different pages. Take a look at the example:





For example, the following code is available in Test.js:





var route = {        _routes: {}, // the  routes will be stored here         add:  function (url, callback)  {            
this._routes[url] = callback;        &NBSP},         run:  function ()  {            jquery.each (this._ Routes, function (pattern)  { // pattern  key that points to the collection of _routes objects, that is, url                  if  (Location.href.match (pattern))  {                     //  "This"  points to the function tO be executed                      this (); //this  points to value that points to a collection of  _routes objects, that is, the method to execute                  }     
        });         }     }     // will  execute only on this page:route.add (' test.html ',  function ()  {  
  alert (' hello there! ');
}); Route.add (' products.html ',  function ()  {    alert ("This won" t be 
executed :(");
});  you can even use regex-es:route.add ('. *.html ',  function ()  {  
  alert (' this is using a regex! ');
}); Route.run ();


Using Logical AND Operator

The use of logic and operators can simplify conditional branching statements, examples:

The general wording:

Instead of writing this:
if ($ (' #elem '). Length) {
//do something
}


Better way to do it:

$ (' #elem '). Length && alert ("doing something");


Very useful jquery is () method

The IS () method is useful to look at some examples:

Html:

<div id= "Elem" ></div>


Js:

Variable save jquery object
var elem = $ (' #elem ');
Judge whether Div
elem.is (' div ') && console.log ("It ' s a div");
Contains the class name. BigBox
elem.is ('. BigBox ') && console.log ("It has BigBox");
Visible
elem.is (': Not (: visible) ') && Console.log ("It is hidden!");
Sets the element to perform an animated
elem.animate ({' width ': 200},1);
Whether to perform animation
elem.is (': Animated ') && Console.log ("It is animated!");


Define a exists function

Determining whether a jquery object exists needs to judge the length attribute, which can be encapsulated as a exists function, simplifying the code and making it easier to read.

Html:

<div id= "Elem" ></div>


Js:

General method
Console.log (' #elem '). length = = 1? "exists!": "Doesn ' t exist!");
Encapsulation method
jQuery.fn.exists = function () {return this.length > 0;}
Console.log (' #elem '). Exists ()? "exists!": "Doesn ' t exist!");


Use the second argument of the $ () function

The $ () function can receive two parameters and what the second parameter does, you can take a look at the following example:

<ul id= "Firstlist" >
<li>one</li>
<li>two</li>
<li>three </li>
</ul>
<ul id= "secondlist" >
<li>blue</li>
<li>gree N</li>
</ul>



Function One:

Select an element by #firstlist limit element to select
$ (' li ', ' #firstList ') only within the current UL node range. each (function () {
Console.log ($ (this)). HTML ());
Equivalent to $ (' #firstList '). Find (' Li ');


Function Two:

Creates an element. The second parameter is the corresponding configuration property, and the JQuery method is executed with the
var div = $ (' <div> ', {
"class": "Bigblue",
"CSS": {
"background-c Olor ":" Purple "
},
" width ":"
height ":"
animate ": {///using jquery method as attribute
" width ": 200 ,
"height":}
);
Div. appendto (' body ');


Cancel Right Click event

$ (function () {
$ (document). On ("ContextMenu", function (e) {
E. preventdefault ();
});
});


Cancel Text selection

Adapts to all browsers
$ (' p.descr '). attr (' unselectable ', ' on ')
. css (' user-select ', ' none ')
. On (' Selectstart ', false);


Resolve anchor Element URL

//  URL to parse var url =  ' http://tutorialzine.com/books/
Jquery-trickshots?trick=12#comments '  ;
  Create a new link through the URL var a = $ (' <a> '  ,{ href:  url });
Console. log (' host name:  '  + a. prop (' hostname '  ));
Console. log (' path:  '  + a. prop (' pathname '  ));
Console. log (' query:  '  + a. prop) (' Search '  );
Console. log (' protocol:  '  + a. prop (' Protocol '  )); Console. log (' hash:  '  + a. prop (' Hash '  ); 




Output:

Host name:tutorialzine.com
Path:/books/jquery-trickshots
Query:? trick=12
Protocol:http:
Hash: #comments





decrypt jquery kernel dom operation

jquery's approach to inserting DOM operations has about 10 kinds of

Append, prepend, before, after, ReplaceWith

Appendto, Prependto, InsertBefore, InsertAfter, ReplaceAll

are divided into 2 groups, up and down control, to achieve the same function. The main differences are the syntax-especially the location of the content and the target

The Dommanip,buildfragment module that it relies on has previously analyzed

to insert the content specified by the parameter after each element in the matching element collection as its sibling node

for. After (), select the expression before the function, and the argument is what you want to insert.

for. InsertAfter (), on the contrary, the content is preceded by the method, and it is placed behind the element in the argument.

after

After:function () {return
this.dommanip (arguments, function (elem) {
if (This.parentnode)
{        This.parentNode.insertBefore (Elem, this.nextsibling);
}
});
},


It's been mentioned before. All methods rely on This.dommanip merge parameter processing, internally through the Buildfragment module to build document fragments

The specific execution of each method is then provided through a callback to handle

The DOM operation does not provide a way to insert a sibling node directly after the current node, but provides a similar method

InsertBefore () Method: You can insert a new child node before an existing child node. Syntax: InsertBefore (Newchild,refchild)

See how jquery handles it.

For example

Inner.after (' <p>Test</p> ');


The inside will build the ' <p>Test</p> ' through buildfragment the document Elem

Then through This.parentNode.insertBefore (Elem, this.nextsibling);

This here is the corresponding inner, Elem is ' <p>Test</p> '

See here is very good understanding of after the implementation of

Simple simulation with native method

var inner = document.getelementsbyclassname (' inner ') for
(var i =0; i<inner.length;i++) {
var elem = inner[ I]
var div = document.createelement (' div ')
div.innerhtml = ' aaaa '
elem.parentNode.insertBefore (div , elem.nextsibling)
}


InsertAfter

The designers of the jquery code are smart enough to incorporate similar functionality as much as possible, and the code is more refined and aesthetically pleasing.

Jquery.each ({
appendto: "Append",
prependto: "prepend",
insertbefore: "Before",
Insertafte R: "After",
ReplaceAll: "replacewith"
}, function (name, original) {
jquery.fn[name] = function (SE lector) {
};
});


DEMO

$ (' <p>Test</p> '). InsertAfter ('. inner ');


A document is built through $ (' <p>Test</p> '), and the object is inserted through the InsertAfter method after all the nodes of class equals inner

The meaning of the expression is the same as after, the main difference is the grammar-especially the position of the content and the target

Jquery.fn[&nbsp;name&nbsp;]&nbsp;=&nbsp;function (&nbsp;selector&nbsp;) &nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp; Elems, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ret&nbsp;=&nbsp;[], &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;insert&nbsp;=&nbsp;jquery (&nbsp;selector&nbsp;), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Last&nbsp;=&nbsp;insert.length&nbsp;-&nbsp;1, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;i&nbsp;=&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;for&nbsp; (&nbsp;;&nbsp;i&nbsp;&lt;=&nbsp;last;&nbsp;i++&nbsp;) &nbsp;{&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;elems&nbsp;=&nbsp;i&nbsp;===&nbsp;last&nbsp;?&nbsp;this&nbsp;:&nbsp;
This.clone (&nbsp;true&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;jquery (&nbsp;insert[&nbsp;i&nbsp;]&nbsp;) [&nbsp;original&nbsp;
] (&nbsp;elems&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;support:&nbsp;qtwebkit &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;//&nbsp;.get () &nbsp;because&nbsp;core_push.apply (_,&nbsp;arRaylike) &nbsp;throws &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;core_push.apply (&nbsp;ret,&nbsp;elems.get (
) &nbsp;);
&NBSP;&NBSP;&NBSP;&NBSP} &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;this.pushstack (&nbsp;ret&nbsp;); };



See the specific implementation method. InsertAfter ('. inner '); Inner was actually introduced as selector.

Selector may just have to be transformed inside the string selector, insert = JQuery (selector),

$ (' <p>Test</p> ') is a constructed document fragment node, so if you give the insert multiple times you need to completely clone a copy, so you directly assign

Elems = i = = last? This:this.clone (TRUE); JQuery (insert[i]) [original] (Elems);

is still the execution after

JQuery (insert[i]) [original] (Elems);

Eventually, you need to return to the new node for this build.

Collect the built nodes

Core_push.apply (ret, elems.get ());


Build a new jquery object to implement the chained

This.pushstack (ret);


It can be seen that the essence of after and InsertAfter is the same, but in different ways

Before ()

Inserts the content before the matching element, based on the parameter settings

Before:function () {return
this.dommanip (arguments, function (elem) {
if (this.parentnode            ) {
This.parentNode.insertBefore (elem, this);
}
});
},


Like after just replacing the second parameter, changing the insertion position


Append ()

Inserts the parameter contents at the end of each matching element

Append:function () {return
this.dommanip (arguments, function (elem) {
if This.nodetype = 1 | | His.nodetype = = 11 | |            This.nodetype = = 9 {
var target = Manipulationtarget (this, elem);
Target.appendchild (elem);
}
});
},


To add nodes internally, you can call the AppendChild method directly

Prepend ()

Inserts the parameter contents before each matching element (inside the element)

Prepend:function () {return
this.dommanip (arguments, function (elem) {
if (This.nodetype = 1 | | This.nodetype = = 11 | |            This.nodetype = = 9 {
var target = Manipulationtarget (this, elem);
Target.insertbefore (Elem, target.firstchild);
}
});
},


Like after just replacing the second parameter, changing the insertion position

ReplaceWith ()

Replaces all matching elements in the collection with the provided content and returns a collection of deleted elements.

. ReplaceWith () can remove content from the DOM and insert new content in this place. Take a look at the following example:

<div class= "Container" >
<div class= "inner A" >Hello</div>
<div class= "inner second" >And</div>
<div class= "inner third" >Goodbye</div>
</div>


We can replace the second inner <div> with the specified HTML:

$ (' Div.second '). ReplaceWith (' 


The results are as follows:

<div class= "Container" >
<div class= "inner A" >Hello</div>


Or we can choose an element to take it as a replacement:

$ (' Div.third '). ReplaceWith ($ ('. a '));


The results are as follows:

<div class= "Container" >
<div class= "inner second" >And</div>
<div class= "inner a" >Hello</div>
</div>


As you can see from this example, the elements used to replace are moved from the old place to the new location, rather than copied.

The. ReplaceWith () method, like most other jquery methods, returns the JQuery object, so it can be used with other methods, but it should be noted that for this method, the object points to an object that has been removed from the DOM, rather than to the replacement object.

Replacewith:&nbsp;function () &nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;var &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;snapshot&nbsp;the&nbsp;dom&nbsp;in&nbsp;case&nbsp;.dommanip&nbsp;sweeps&nbsp;something&nbsp;relevant &nbsp;into&nbsp;its&nbsp;fragment &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;args&nbsp;=&nbsp;jquery.map ( &nbsp;this,&nbsp;function (&nbsp;elem&nbsp;) &nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;return&nbsp;[&nbsp;elem.nextSibling,&nbsp;elem.parentNode&nbsp;]; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}), &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;i&nbsp;=
&nbsp;0; &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;make&nbsp;the&nbsp;changes,&nbsp;replacing&nbsp;each&nbsp;context&nbsp;element &nbsp;with&nbsp;the&nbsp;new&nbsp;content &nbsp;&nbsp;&nbsp;&nbsp;this.dommanip (&nbsp;arguments,&nbsp;function ( &nbsp;elem&nbsp;) &nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;next&nbsp;=&nbsp;args[&nbsp;i ++&nbsp;], &NBSP;&NBSP;&NBSP;&NBsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parent&nbsp;=&nbsp;args[&nbsp;i++&nbsp;]; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp; (&nbsp;parent&nbsp;) &nbsp;{&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;don ' t&nbsp;use&nbsp;the&nbsp;snapshot&nbsp;next&nbsp; if&nbsp;it&nbsp;has&nbsp;moved&nbsp; (#13810) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;if&nbsp; (&nbsp;next&nbsp;&amp;&amp;&nbsp;next.parentNode&nbsp;!==&nbsp;parent&nbsp;) &nbsp;{&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;next&nbsp;=&nbsp;
this.nextsibling; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;jquery (&nbsp;this&nbsp;). Remove (); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;parent.insertbefore (&nbsp;elem,&nbsp;
next&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;Allow&nbsp;new&nbsp;content&nbsp;to&nbsp;include&nbsp;elements&nbsp;from&nbsp;
The&nbsp;context&nbsp;set &nbsp;&nbsp;&nbsp;&nbsp;},&nbsp;true&nbsp;); &nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;force&nbsp;removal&nbsp;if&nbsp;there&nbsp;was&nbsp;no&nbsp;new&nbsp;content &nbsp; (e.g.,&nbsp;from&nbsp;empty&nbsp;arguments) &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;i&nbsp;?&nbsp;this&nbsp;:
&nbsp;this.remove (); },


Deletes the target node

JQuery (this). Remove ();

and then insert a new node

Parent.insertbefore (Elem, next);

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.