I. DOM create node and node properties
JavaScript makes it easy to get a DOM node for a series of DOM operations. But in fact, the general developers are accustomed to the first definition of HTML structure, but this is very inflexible.
Consider this scenario: if we get the data through Ajax before we can determine the structure, this situation requires a dynamic processing node.
This article shows you how to use JavaScript to create div node elements, mainly including the creation of the div node element attributes and the creation of the DIV node elements of the style of the two most of the content, I believe this article will certainly let you have some gains.
Introduce some native methods provided by the browser you need to use (not dealing with the low-version IE compatibility problem here)
The creation process is relatively simple and generally follows:
- Creating nodes (Common: elements, attributes, and text)
- Add some properties of a node
- Adding to the document
A little bit of the approach involved in the process:
- Create element: Document.createelement
- Setting Properties: SetAttribute
- Add text: InnerHTML
- Add to Document: AppendChild
As shown in the code on the right, write a simplest element to create, and we'll find a few questions:
- Each element node must be created separately
- A node is a property that needs to be set separately, and the interface set is not very uniform
- Not flexible to add to the specified element location
- Finally, one of the most important: Browser compatibility problem handling
Two. jquery node creation and handling of attributes
To Create an element node :
There are several ways that you can get in touch later. It is common to give the structure of this node directly to the HTML tag string, which is handled by the $ () function, $ ("HTML structure")
$ ("<div></div>")
Create as this node :
Similar to creating element nodes, you can directly describe the contents of the text
$ ("<div> I am a text node </div>")
Create as attribute node :
The same way you create an element node
$ ("<div id= ' test ' class= ' Aaron ' > I am a text node </div>")
We've transformed the previous code through jquery, as shown in the code on the right.
It's all done in one sentence, the same way you write HTML structure.
$ ("<div class= ' right ' ><div class= ' Aaron ' > dynamically create DIV element nodes </div></div>")
This is how jquery creates nodes, and lets us preserve the way HTML is structured, very simple, convenient and flexible
Three. Inside the DOM insert append () and Appendto ()
The dynamically created element is not enough, it is only temporarily stored in memory, and eventually we need to put it on the page document and render it. So here's the question, how do I put it on the document?
This involves a positional relationship, and it is common to put the newly created element as a child of one element of the page into its interior. For such processing, jquery defines 2 methods of operation
Append: This operation is similar to the case when you perform native appendchild methods on the specified elements, adding them to the document.
AppendTo: In fact, using this method is reversed by the normal $ (A). Append (b) operation, that is, instead of appending B to a, instead of appending A to B.
A simple summary is:
. append () and. AppendTo () Two methods function the same, the main difference is the syntax--the content and the location of the target is different
Append () is preceded by the inserted object, followed by the element content to be inserted inside the object Appendto () preceded by the element content to be inserted, followed by the inserted object
Four. Inserting before () outside the DOM node and after ()
There are various relationships between nodes and nodes, except father and son, ancestral relationships, and brotherhood. Before we were dealing with the insertion of a node, we were exposed to several methods of internal insertion, and this section began with the processing of external insertions, the relationship between siblings, where jquery introduced 2 methods that can be used to insert content before and after the element that matches I
Description of the selector:
- Before and after are used to add adjacent sibling nodes to the outside of the selected element
- All 2 methods can receive an HTML string, a DOM element, an array of elements, or a jquery object, used to insert in front of or behind each matching element in the collection
- 2 methods support multiple Parameters pass after (Div1,div2,....) can refer to the right case code
Note the point:
- After the element is added after the HTML code, if there is an element behind the element, then move the following element back, and then insert the HTML code
- Before add HTML code to the front of the element, and if the element is preceded by an element, move the preceding element forward, then insert the HTML code
Five. Insert prepend () and Prependto () inside the DOM
The method of manipulating inside an element, in addition to inserting the specified content through append and appendto at the end of the selected element (still inside), can also be inserted before the selected element, and jquery provides the method prepend and Prependto
Description of the selector:
You can see the use and difference of prepend and prependto through the right code:
- The. Prepend () method inserts the specified element into the matching element as its first child element (if you want to insert as the last child element with. Append ()).
- . prepend () and. Prependto () to achieve the same functionality, the main difference is the syntax, the inserted content and the location of the target is different
- For. Prepend (), the selector expression is written in front of the method, as a container for the content to be inserted, and the content to be inserted as the parameter of the method
- and. Prependto () on the contrary, the content to be inserted is written in front of the method, either as a selector expression or as a dynamically created tag, as a parameter for the container to insert the content.
Here is a summary of the differences in the internal operation of the four methods:
- Append () appends content to each matching element
- Prepend () internal front content to each matched element
- AppendTo () Appends all matching elements to the collection of another specified element
- Prependto () puts all matching elements in front of another specified set of elements
Six. External DOM Insert InsertAfter () and InsertBefore ()
As with internal insert processing, jquery adds 2 new methods to the location of the content targets InsertAfter and InsertBefore
- . before () and. InsertBefore () Implement the same functionality. The main difference is the syntax--the location of the content and the target. For the Before () selection expression in front of the function, the contents as arguments, and. InsertBefore () Just the opposite, the content is in front of the method, it will be placed in front of the element in the argument
. After () and. InsertAfter () Implement the same functionality. The main difference is the syntax-especially (inserting) the content and the location of the target. For After () Select an expression in front of the function, the argument is what will be inserted. For. InsertAfter (), just the opposite, the content is in front of the method, it will be placed behind the element in the parameter
- Before, after and InsertBefore. InsertAfter does not support multi-parameter processing in addition to the target and location
Precautions:
- InsertAfter Inserts the jquery encapsulated element behind the specified element, and if there is an element behind it, move the trailing element back and insert the jquery object;
- InsertBefore inserts the jquery encapsulated element in front of the specified element, and if the element is preceded by an element, move the preceding element forward, then insert the jquery object;
Seven. Basic usage of the empty () Dom node deletion
To remove a node on a page is a common practice for developers, jquery offers several different ways to handle this problem, here we take a closer look at the next empty method
Empty, as the name implies, clears the method, but is a little different from the deletion, because it only removes all child nodes in the specified element.
This method not only removes the child elements (and other descendant elements), but also removes the text from the element. Because, according to the instructions, any text string in the element is considered to be a child of that element. Take a look at the following HTML:
<div class= "Hello" ><p> mu class network </p></div>
If we remove all the elements of the div in the empty method, it simply empties the internal HTML code, but the markup remains in the DOM
Handle $ ('. Hello ') through empty. Empty ()//Results:<p> </p> was removed <div class= "Hello" ></div>
Eight. Removal of the DOM delete node has participation in no argument
Remove, like empty, is the method of removing elements, but remove removes the element itself and removes everything inside the element, including the bound event and the jquery data associated with the element.
For example, a node, binding a point-and-click event
<div class= "Hello" ><p> mu class net </p></div>$ ('. Hello '). On ("click", fn)
If you do not delete this node through the Remove method is also very simple, but also need to destroy the event, here is to prevent "memory leaks", so the front-end developers must pay attention to how many events tied, do not have to remember to destroy
Removing the DIV and all its internal elements through the Remove method automatically actions the event destruction method, so it is very easy to use.
Handle $ ('. Hello ') through Remove. Remove ()//Result: <div class= "Hello" ><p> mu class net </p></div> all removed//node does not exist, Colleague incidents will be destroyed, too.
Remove expression parameter:
Remove is a good place to pass a selector expression to filter the collection of matching elements that will be removed, optionally deleting the specified node
We can do this by selecting a set of identical elements through $ () and passing the filtered rules through remove ().
In contrast to the code area on the right, we can handle this by similar
$ ("P"). Filter (": Contains (' 3 ')"). Remove ()
To remove the specified element, jquery provides two methods for empty () and remove ([expr]), and two deletes the element, but there is a difference between the two.
Empty Method
- Strictly speaking, the empty () method is not to delete a node, but to empty the node, which empties all descendant nodes in the element
- Empty cannot delete itself this node
Remove Method
- The node and all descendant nodes that the node contains will be deleted at the same time
- Provides an expression that passes a filter, removing elements from a specified collection
The above is the difference between the two, we specifically through the right part of the code to deepen understanding
Nine. delete operation of the DOM delete node's retention data detach
If we want to temporarily delete the nodes on the page, but do not want the data and events on the node to be lost, and can let the deleted node display to the page in the next time period, we can use the detach method to handle
Detach is literally easy to understand. Let a Web element be hosted. That is, the element is removed from the current page, but the memory model object of the element is preserved.
Take a look at the explanation of the official jquery document:
This method 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. $ ("div"). Detach () This sentence will remove the object, only the display effect is not. But it still exists in memory. When you're append, you're back in the flow of the document. It shows up again.
Of course, it is important to note that thedetach method is unique to jquery, so it can only handle events or data that are bound by the jquery method .
Query is a very strong tool library, and in the development of work, some methods are ignored because they are not commonly used or are not noticed.
Remove () and detach () may be one of them, maybe remove () we use more, and detach () may be less
Explain the difference between 2 methods through a comparison table
Method name |
Parameters |
Whether the event and data have also been removed |
Whether the element itself is removed |
Remove |
Support Selector expression |
Is |
Yes (when there is no parameter), the range to be covered by the parameter when there are parameters |
Detach |
Parameter same as remove |
Whether |
Situation with remove |
Remove : Removing nodes
- Without parameters, removes the entire node of itself and all nodes inside that node, including events and data on the node
- has parameters to remove the filtered node and all nodes inside the node, including events and data on the node
Detach : Removing nodes
- Removed processing is consistent with remove
- Unlike remove (), all bound events, attached data, and so on will remain
- For example: $ ("P"). Detach () This sentence will remove the object, only the display effect is not. But it still exists in memory. When you're append, you're back in the flow of the document. It shows up again.
10. Dom Copy Clone ()
Cloning nodes is a common dom operation, and JQuery provides a clone method that is designed to handle the cloning of the DOM
The. Clone () method deeply copies all matching element collections, including all matching elements, subordinate elements of matching elements, and literal nodes.
The Clone method is relatively simple is the cloning node, but it should be noted that if the node has events or other processing data, we need to pass a Boolean value through Clone (ture) ture used to specify, so not only to clone the simple node structure, And we're going to clone the accompanying incident with the data.
For example:
The HTML section <div></div>javascript part $ ("div"). On (' click ', function () {///Perform action})//clone process a $ ("div"). Clone () //Clone only structure, event loss//clone processing two $ ("div"). Clone (TRUE)//structure, event and data cloning
The use of this is so simple that using clones we need to know extra details:
- Clone () method, before inserting it into a document, we can modify the cloned element or element content, such as the right code I $ (this). Clone (). CSS (' Color ', ' red ') adds a color
- Copies all event handlers bound on the original element to the cloned element by passing true
- The Clone () method is a jquery extension that only handles events and data that are bound by jquery
- The objects and arrays within the element data are not copied and will continue to be shared by the cloned element and the original element. Deep copy of all the data, you need to manually copy each
Eleven. Dom replaces ReplaceAll () and ReplaceWith ()
Previously, we learned how to insert, insert, and delete nodes, and this section will learn how to replace ReplaceWith
. ReplaceWith (newcontent): Replaces all matching elements in the collection with the provided content and returns the collection of deleted elements
Simply put: Select Node A with $ (), call the ReplaceWith method, pass in a new content B (HTML string, Dom element, or jquery object) to replace the selected Node A
See a simple example: a piece of HTML code
<div> <p> First segment </p> <p> second segment </p> <p> third paragraph </p></div>
Replace the node and contents of the second paragraph
$ ("P:eq (1)"). ReplaceWith (' <a style= ' color:red ' > replace the contents of the second paragraph </a> ')
Using jquery to filter out the second P element, call ReplaceWith to replace, the result is as follows
<div> <p> First paragraph </p> <a style= "color:red" > Replace the contents of the second paragraph </a> ' <p> the third paragraph </ P></div>
. ReplaceAll (target) : replaces each target element with a collection of matching elements
The. ReplaceAll () and. ReplaceWith () functions are similar, but the target and source are the opposite, using the HTML structure above, we use the ReplaceAll processing
$ (' <a style= ' color:red ' > replace the contents of the second paragraph </a> '). ReplaceAll (' P:eq (1) ')
Summarize:
- The. ReplaceAll () and. ReplaceWith () functions are similar, mainly the location differences between the target and the source
- The. replacewith () and. ReplaceAll () methods remove all data and event handlers associated with the node
- The. ReplaceWith () method, like most other jquery methods, returns a JQuery object, so you can link to it with other methods
- The. ReplaceWith () method returns a JQuery object that references the node before the replacement, not the node that was replaced by the Replacewith/replaceall method
Twelve. Dom Parcel Warp (), Unwarp () and Warpall ()
If you are wrapping an element with another element, that is, adding a parent element to it, jquery provides a wrap method for this processing
. Wrap (wrappingelement) : Wraps an HTML structure around each element that matches in the collection
Simply look at the code:
<p>p Elements </p>
Add a div package to the P element
$ (' P '). Wrap (' <div></div> ')
Last structure, p element adds a parent div structure
<div> <p>p Elements </p></div>
. Wrap (function) : A callback function that returns the HTML content or JQuery object used to wrap the matching elements
The effect after use is the same as the direct pass parameter, except that the code can be written in the body of the function, in a different way.
Take the first case as an example:
$ (' P '). Wrap (function () { return ' <div></div> '; Similar to the first one, but not in the same notation})
Attention:
The. Wrap () function can accept any string or object that can be passed to the $ () factory function to specify a DOM structure. This structure can be nested several layers deep, but should contain only one core element. Each matching element will be wrapped in this structure. The method returns the original set of elements so that the chained method is used later.
We can add the parent element of a package to the selected element through the Wrap method. Conversely, what do you do if you delete the parent element of the selected element?
jquery provides a unwrap () method that is the opposite of the Wrap method. Deletes the parent element of the matching element collection, preserving itself (and the sibling element, if present) in its original position.
See a simple case:
<div> <p>p Elements </p></div>
I'm going to remove the div from this code, and the general method will go directly through the Remove or empty method
$ (' div '). Remove ();
But if I have to keep the internal element p, which means more processing is needed, the steps are more cumbersome and, for the sake of convenience, jquery provides the unwrap method to handle the problem conveniently.
$ (' P '). Unwrap ();
Find the P element and then call the Unwrap method, which will only delete the parent div element.
Results:
<p>p Elements </p>
Wrap is handled for a single DOM element, and if you want to wrap the elements of the collection with other elements, that is, to add a parent element to them, jquery provides a wrapall method for such processing.
. Wrapall (wrappingelement) : adds an outer wrapping HTML structure to the matching elements in the collection
Simply look at the code:
<p>p element </p><p>p element </p>
Add a div package to all P elements
$ (' P '). Wrapall (' <div></div> ')
The last structure, 2 p elements have added a parent div structure
<div> <p>p elements </p> <p>p elements </p></div>
. Wrapall (function) : A callback function that returns the HTML content or JQuery object used to wrap the matching elements
Each element can be processed individually by means of a callback
Take the above case as an example,
$ (' P '). Wrapall (function () { return ' <div><div/> ';})
The result of the above notation is the same as that of warp.
<div> <p>p elements </p></div><div> <p>p elements </p></div>
Attention:
The. Wrapall () function can accept any string or object that can be passed to the $ () factory function to specify a DOM structure. This structure can be nested multiple layers, but the inner layer can have only one element. All matching elements will be treated as a whole, and wrapped in the specified HTML structure outside the whole.
Jquery-dom article