The foundation of jquery--dom Chapter

Source: Internet
Author: User

The foundation of jquery--dom Chapter

How do I create a node in JavaScript?

    1. Creating nodes (Common: elements, attributes, and text)
    2. Add some properties of a node
    3. Adding to the document

A little bit of the approach involved in the process:

    • To create an element:document.createElement
    • To set properties:setAttribute
    • Add text:innerHTML
    • To add a document:appendChild

Example:

    document.addEventListener(‘click‘,function(){        //创建2个div元素        var rightdiv = document.createElement(‘div‘)        var rightaaron = document.createElement("div");        //给2个div设置不同的属性        rightdiv.setAttribute(‘class‘, ‘right‘)        rightaaron.className = ‘aaron‘        rightaaron.innerHTML = "动态创建DIV元素节点";        //2个div合并成包含关系        rightdiv.appendChild(rightaaron)        //绘制到页面body        body.appendChild(rightdiv)    },false)

And it's easy to use jquery:

$body.on(‘click‘, function() {    //通过jQuery生成div元素节点    var div = $("<div class=‘right‘><div class=‘aaron‘>动态创建DIV元素节点</div></div>")    $body.append(div)})
Insertion of DOM nodes inside insert append () and Appendto ()
$(".content").append(‘<div class="append">通过append方法添加的元素</div>‘)$(‘<div class="appendTo">通过appendTo方法添加的元素</div>‘).appendTo($(".content"))
External insert after () with before () Selector
SelectorDescription
.after( content ) Inserts the content specified by the parameter after each element in the matching element collection as its sibling node
.before( content ) According to the parameter setting, insert the content before the matching element

Before and after are used to add adjacent sibling nodes to the outside of the selected element

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
Internal Insert prepend () and Prependto () Selector
SelectorDescription
Prepend Internal front content to each matched element
Prependto Place all matching elements in front of another specified set of elements
External Insert InsertAfter () and InsertBefore () Selector
SelectorDescription
InsertBefore Inserts each matching element in the collection before the target element
InsertAfter Inserts each matching element in the collection after the target element

before()The selection expression precedes the function, the content is the argument, and the content is in front of the .insertBefore() method, and it is placed in front of the element in the argument.

    //在test1元素前后插入集合中每个匹配的元素    //不支持多参数    $(‘<p style="color:red">测试insertBefore方法增加</p>‘, ‘<p style="color:red">多参数</p>‘).insertBefore($(".test1"))
Basic usage of Delete empty () for DOM node

empty()Removes all child nodes from the specified element.

The parameter and non-argument usage of remove ()

Remove () Removes the element itself, and it also removes everything inside the element, including the bound event and the jquery data associated with the element.
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

$("button:last").on(‘click‘, function() {    //找到所有p元素中,包含了3的元素    //这个也是一个过滤器的处理    $("p").remove(":contains(‘3‘)")})
Delete operation to preserve data detach ()

detach()This method does not remove the matching elements from the jquery object, so that the matching elements can be used in the future. In contrast remove() , all bound events, attached data, and so on are preserved.
$("div").detach()This sentence removes the object, only the display effect is gone. But it still exists in memory. appendafter that, you're back in the document flow. It shows up again.

var p;$("#bt1").click(function() {    if (!$("p").length) return; //去重    //通过detach方法删除元素    //只是页面不可见,但是这个节点还是保存在内存中    //数据与事件都不会丢失    p = $("p").detach()});$("#bt2").click(function() {    //把p元素在添加到页面中    //事件还是存在    $("body").append(p);});
Copy and replace DOM copy Clone () of DOM node

.clone()The method deeply copies all matching elements, including all matching elements, subordinate elements of matching elements, and text 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.

HTML部分<div></div>JavaScript部分$("div").on(‘click‘, function() {//执行操作})//clone处理一$("div").clone()   //只克隆了结构,事件丢失//clone处理二$("div").clone(true) //结构、事件与数据都克隆

Cloning nodes and cloning events

<script type="text/javascript">    //克隆节点    //克隆事件    $(".aaron2").on(‘click‘, function() {        console.log(1)        $(".left").append( $(this).clone(true).css(‘color‘,‘blue‘) )    })</script>
Dom replaces ReplaceWith () and ReplaceAll ()

.replaceWith( newContent ): Replaces all matching elements in the collection with the provided content and returns the collection of deleted elements

$(".bt1").on(‘click‘, function() {    //找到内容为第二段的p元素    //通过replaceWith删除并替换这个节点    $(".right > div:first p:eq(1)").replaceWith(‘<a style="color:red">replaceWith替换第二段的内容</a>‘)})

.replaceAll( target ): replaces each target element with a collection of matching elements

$(".bt2").on(‘click‘, function() {    $(‘<a style="color:red">replaceAll替换第六段的内容</a>‘).replaceAll(‘.right > div:last p:last‘);})

.replaceAll().replaceWith()similar to function, mainly the location difference between the target and the source

Dom Wrapping Wrap () method

.wrap( wrappingElement ): Wraps an HTML structure around each element that matches in the collection

$(‘p‘).wrap(‘<div></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 inside of the function body, in a different way.

$(‘p‘).wrap(function() {    return ‘<div><div/>‘;   //与第一种类似,只是写法不一样})
Dom Wrap Unwrap () method

Deletes the parent element of the matching element collection, preserving itself (and the sibling element, if present) in its original position.

$(‘p‘).unwarp();
Dom Wrap Wrapall () method

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元素</p><p>p元素</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元素</p>    <p>p元素</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元素</p></div><div>    <p>p元素</p></div>
Dom Wrap Wrapinner () method

If you want to wrap all the child elements within a set of elements with other elements and act as child elements of the specified element, jquery provides a Wrapinner method for such processing.

. Wrapinner (wrappingelement): Adds the HTML structure of the package to the interior of the matched element in the collection

Sounds a bit around, you can use a simple example to describe, a simple look at a piece of code:

<p>p元素</p><p>p元素</p>

Add a div package to all P elements

$(‘p‘).wrapInner(‘<div></div>‘)

The final structure, the inner element of the matching p element is wrapped by a div

<p>    <div>p元素</div></p><p>    <div>p元素</div></p>

. Wrapinner (function) : Allows us to use a callback function to make arguments, each time a matching element is encountered, the function is executed, returning a DOM element, jquery object, or HTML fragment, to wrap the content of the matching element

Take the above case as an example,

$(‘p‘).wrapInner(function() {    return ‘<div><div/>‘; })

The result of the above notation is the same as the first processing

<div>    <p>p元素</p></div><div>    <p>p元素</p></div>
jquery traversal Children () method

If you want to quickly find the first level of child elements in a collection, you can use the method at this point children() . It is important to note that the .children(selector) method is to return all child elements of each element in the matching element collection ( sons only, which is understood to be the father-son relationship )

$("#bt1").click(function() {    $(‘.div‘).children().css(‘border‘, ‘1px solid red‘);})
Find () method

If you want to quickly find the descendant elements of these elements in the DOM tree, you can use methods at this point find() , which is also a very high-frequency method of development. Notice the difference between the children and the Find method, children is a parent-child relationship lookup, and find is a descendant relationship (including a parent-child relationship)
.find() methods to pay attention to the knowledge points :

    • Find is a descendant of each element in the current collection of elements. As long as they meet, whether they are sons, grandchildren can.
    • Unlike other tree traversal methods, the selector expression .find() is required for parameters. If we need to implement a retrieval of all descendant elements, we can pass the wildcard selector ' * '.
    • Find is only traversed in descendants, not including itself.
    • The selector context is .find() implemented by the method; $(‘li.item-ii‘).find(‘li‘) $(‘li‘, ‘li.item-ii‘)

      <script type="text/javascript">$("button:last").click(function() {    //找到所有p元素,然后筛选出子元素是span标签的节点    //改变其字体颜色    var $spans = $(‘span‘);    $("p").find($spans).css(‘color‘, ‘red‘);})</script>
The parent () method

If you want to quickly find the parent element of each element in the collection (which is understood to be the father-son relationship), you can use the parent () method
Because it is a parent element, this method only looks up the first level

<script type="text/javascript">$("button:last").click(function() {    //找到所有class=item-a的父元素    //然后给每个ul,然后筛选出最后一个,加上蓝色的边   $(‘.item-a‘).parent(‘:last‘).css(‘border‘, ‘1px solid blue‘)})</script>
Parents () method

The parent will only find one level, and parents will always look up to find the ancestor node

1. parents() And the .parent() method is similar, but the latter just makes a single-level DOM tree Lookup
$( "html" ).parent()the 2 method returns a contained document collection and $( "html" ).parents() returns an empty collection.

Closest () method

closest()Method accepts a selector string for a matching element
From the beginning of the element itself, match the ancestor elements on the DOM tree and return the first matching ancestor

For example, in a DIV element, looking up all the LI elements, you can express

$("div").closet("li‘)
Next () method

Quickly finds the collection of elements of the next sibling element immediately following each element in the specified element collection, at which point next()

Understanding Node Lookup relationships :
The following class= "item-1" element is the red part, and the blue class= "Tem-2" is its sibling element.

<ul class="level-3">    <li class="item-1">1</li>    <li class="item-2">2</li>    <li class="item-3">3</li></ul>
Prev () method

Quickly finds the collection of elements of the preceding sibling elements that are immediately adjacent to each element in the specified element collection, at which point the prev() method

Siblings ()

Quickly finds the next sibling element immediately preceding each element in the specified meta-set, at which point the siblings() method

Understanding Node Lookup relationships :

The following is the LI element of the blue class= "Tem-2", the red node is its siblings sibling node

<ul class="level-3">    <li class="item-1">1</li>    <li class="item-2">2</li>    <li class="item-3">3</li></ul>
Add () method

jquery is a collection object that can perform a series of operations after the specified element collection is found through the $ () method. $()after that, it means that the collection object is already deterministic, and if you need to add a new element to the collection later, how do you deal with it? jquery provides an Add method for creating a new jquery object that is added to the collection of matching elements

.add()Parameters can be almost accepted $() , including a jquery selector expression, a DOM element, or an HTML fragment reference.

Simply look at a case:

Action: Select all the LI elements and then add the P element to the Li's concentration

<ul>    <li>list item 1</li>    <li>list item 3</li></ul><p>新的p元素</p>

Process one: Pass Selector

$(‘li‘).add(‘p‘)

Handling two: Passing DOM elements

$(‘li‘).add(document.getElementsByTagName(‘p‘)[0])

Another way is to dynamically create a P tag to join the collection and then insert it into the specified position, but this changes the arrangement of the elements themselves.

 $(‘li‘).add(‘<p>新的p元素</p>‘).appendTo(目标位置)
each ()

jquery is a collection of objects that $() can perform a series of actions after finding the specified collection of elements. For example, we manipulate $("li").css(‘‘) all Li to set the style value because jquery is a collection object, so the inside of a CSS method must encapsulate a traversal method, called an implicit iterative process. To set a color for each Li in a collection, here's how each

.each()The method is a for loop iterator that iterates through each DOM element in the JQuery object collection. Each time the callback function executes, the current number of cycles is passed as a parameter (counting starting from 0

So in general we know 3 key points:

each是一个for循环的包装迭代器each通过回调的方式处理,并且会有2个固定的实参,索引与元素each回调方法中的this指向当前迭代的dom元素

Look at a simple case.

<ul>    <li>慕课网</li>    <li>Aaron</li></ul>

Start Iteration Li, Loop 2 times

$("li").each(function(index, element) {     index 索引 0,1     element是对应的li节点 li,li     this 指向的是li})

This can be done in the loop to do some logical operation, if you need to exit early, can be returned false in order to abort within the callback function

The foundation of jquery--dom Chapter

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.