Basic Jquery tutorial-DOM operation_jquery-js tutorial

Source: Internet
Author: User
We all know that dom is an interface unrelated to browsers, platforms, and languages. Using dom interfaces, you can easily access all the standard components on the page, this article mainly explains dom operations in basic jquery tutorials. If you need dom operations, you can refer to the full name of DOM. dom is short for Document Object Model, this indicates the Document Object Model. DOM is an interface unrelated to browsers, platforms, and languages. Using dom interfaces, you can easily access all standard components on the page. Dom operations can be divided into DOM Core, HTM-Dom, and CSS-DOM.

Every webpage can be represented by DOM, and every DOM can be regarded as a DOM tree. The following html page structure can be used to construct a DOM tree. Code:

The Code is as follows:

 
 DOM Demo 

What is your favorite fruit?

  • Apple
  • Orange
  • Pineapple

The constructed DOM tree is as follows:

  

DOM operations in JQuery mainly include: Create, add, delete, modify, and search for database operations ]. The following DOM Operations perform the JQueryDOM learning operation on the preceding DOM tree.

 I. Search for DOM nodes

It is very easy to find nodes. You can easily complete various search tasks by using selector. For example, find the Element Node p and return the text content in p $ ("p "). text (); example: Find the attribute of Element Node p and return the attribute value corresponding to the attribute name $ ("p "). attr ("title"), returns the value of the property title of p.

 2. Create-create a DOM Node

1. Create element nodes

Create an element node and use the node

    Add the child nodes of the element to the DOM node tree. First, create an element point. Create an element node using Jquery's factory function $ (). The format is as follows: $ (html). This method returns a DOM object based on the input html string, and wrap the DOM object into a JQuery object and return it.

    The JQuery code for creating an element node is as follows:

     $li1=$("
  • ")

    $ Li1 is a JQuery object encapsulated by a DOM object. The JQuery code for adding a new node to the DOM tree is as follows:

    $("ul").append($li1); 

    You can only see

  • The default element "·". Because no text is added to the node, only the default symbol is displayed. The text node is created below.

    PS: The append () method is to add a DOM node. For details, see add-Add a DOM node.

    2. Create a text node

    Use the JQuery factory function $ () to create a text node. The JQuery code for creating a text node is as follows:

    $ Li2 = $ ("
  • Apple
  • ");

    The Code returns $ li2, which is a JQuery object encapsulated by the DOM object. Add the new text node to the DOM tree. The JQuery code is as follows:

    $("ul").append($li2);

    After adding the node, You can see "· Apple" on the page. Right-click to view the page source code and find that the newly added text node has no title attribute. The following method creates a node with attributes.

    3. Create an attribute node

    You can use the JQuery factory function to create an attribute node like an element node or a text node. The JQuery code for creating an attribute node is as follows:

    $ Li3 = $ ("
  • Durian
  • ");
        

    The Code returns $ li3, which is also a JQuery object encapsulated by the DOM object. Add the newly created attribute node to the DOM tree. The JQuery code is as follows:

    $("ul").append($li3);

    After adding the node, You can see "· durian" on the page. Right-click to view the source code of the page and find that the newly added property node has the title = 'durian' attribute.

       3. Add-add DOM nodes

    It does not make sense to add the dynamic creation element to the document. There are multiple methods to insert the newly created node into the document: append (), appendTo (), prepend (), prependTo (), after (), insertAfter (), before (), insertBefore ().

    1. append () method

    The append () method adds content to the matching element as follows:

    $("target").append(element);

    Example:

    $ ("Ul"). append ("
  • Bananas
  • ");

    This method finds the ul element and then adds the newly created li element to ul.

    2. appendTo () method

    The appendTo () method appends all matching elements to the specified element. This method is the inverse of the append () method [the inverse of the subject is not the result of the operation. The method is as follows: $ (element). appendTo (target); example:

    $ ("
  • Lychee
  • "). AppendTo (" ul ");
  • This method creates a new element li and adds li to the searched ul element.

    3. prepend () method

    The prepend () method is used to add the elements before each matching element. The method is as follows:

    $(target).prepend(element);

    Example:

    $ ("Ul"). prepend ("
  • Mango
  • ")

    This method searches for the element ul and then inserts the newly created li element into ul as the ul sub-node and as the first sub-node of ul.

    4. prependTo () method

    The prependTo () method adds an element to the front of each matching element. The method is as follows:

    $(element).prependTo();

    Example:

    $ ("
  • Watermelon
  • "). PrependTo (" ul ");

    This method inserts the newly created element li into the searched ul element as the first child element of ul.

    5. after () method

    The after () method adds an element to the matched element, and the newly added element serves as the adjacent sibling element after the target element. The method is as follows:

    $(target).after(element);

    Example:

    $ ("P"). after ("new addition Section new addition section ");

    The method searches for node p, and adds the newly created element to the end of the span node as the p sibling node.

    6. insertAfter () method

    The insertAfter () method inserts the new element into the target element to act as the sibling node of the target element. The method is as follows:

    $(element).insertAfter(target);

    Example:

    $ ("

    InsertAfter operation

    "). InsertAfter (" span ");

    Method to add the newly created p element to the end of the target element span as the first sibling node after the target element.

    7. before () method

    The before () method is inserted before each matching element as the first sibling node of the matching element. The method is as follows:

    $(target).before(element);

    Example:

    $ ("P"). before ("the following section ");

    The before method searches for each element p and inserts the newly created span element into element p as the previous sibling node of p.

    8. insertBefore () method

    The insertBefore () method adds the new element to the target element and acts as the first sibling node of the target element. The method is as follows:

    $(element).insertBefore(target);

    Example:

    $ ("Anchor"). insertBefore ("ul ");

          InsertBefore ()Create Element a and add the new element a to element ul as the former brother node of ul.

    The first four methods for adding an element are added to the element, and the last four are operations for adding an element to the element. These methods can complete element addition in any form.

       4. Delete-delete DOM nodes

    If you want to delete an element in the document, JQuery provides two methods to delete nodes: remove () and empty ();

    1. remove () method

    The remove () method deletes all matched elements. The input parameters are used to filter elements. This method can delete all child nodes in the element. When the matched nodes and their descendants are deleted, the return value of this method is a reference to the deleted node. Therefore, you can use this reference before using these deleted elements.

    The method is as follows:

    $(element).remove();

    Example:

     $span=$("span").remove();      $span.insertAfter("ul");

    In this example, delete all span elements, use $ span to receive the deleted elements, and add the deleted elements to ul as ul's sibling nodes. This operation is equivalent to moving all span elements and descendant elements behind ul.

    2. empty () method.

    Strictly speaking, the empty () method does not delete elements. Instead, it only clears nodes and can clear all child nodes in the elements. The method is as follows:

    $(element).empty();

    Example:

    $("ul li:eq(0)").empty();

    This example uses the empty method to clear the text value of the first li in ul. Only the default symbol "·" of the li label can be entered.

      V. Modify-Modify DOM node operations

    You can modify the element nodes in the document by copying nodes, replacing nodes, and wrapping nodes.

    1. Copy node $ (element). clone ()

    The copy node method can copy node elements and determine whether to copy node elements based on parameters. The method is as follows:

    $(element).clone(true);

    Example:

    $("ul li:eq(0)").clone(true);

    This method copies the first li element of ul. The true parameter determines that the element behavior is also copied when the element is copied. If the behavior is not copied, there is no parameter.

    2. Replace node $ (element). repalcewith (), $ (element). repalceAll ()

    The node replacement method can replace a node in two forms: replaceWith () and replaceAll (). use the replaceWith method to replace the previous element with the subsequent element. replaceAll method replaces the subsequent element with the previous element,

    The method is as follows:

    $(oldelement).replaceWith(newelement);$(newelement).repalceAll(oldelement);

    Example:

    $ ("P"). replaceWith ("I want to stay");

    This method replaces the p element with the strong element.

    $ ("Replace strong"). repalceAll ("strong ");

    In this example, all strong elements are replaced with h3 elements.

    3. Package nodes $ (element). wrap (), $ (element). wrapAll (), $ (element). wrapInner ()

    The wrap node method uses other labels to wrap the target element to change the display form of the element, and this operation does not damage the meaning of the original document. Three methods are available for package nodes.: Wrap (); wrapAll (); wrapInner ();

    The wrap () method is as follows:

    $(dstelement).wrap(tag);

    Example:

    $("p").wrap("");

    This example uses the B label to wrap all p elements. Each element uses the B label to wrap.

    The wrapAll () method is as follows:

    $(dstelement).wrapAll(tag);

    Example:

    $("p").wrapAll("");

    The access example uses B label to wrap all p elements, and all p element labels use a B label to wrap.

    The wrapInner () method is as follows:

    $(dstelement).wrapInner(tag);

    Example:

     $("strong").wrapInner("");

    This example uses the B label to enclose the child elements of each strong element.

    Other operations of Dom elements: attribute operations, style operations, setting and obtaining HTML, text and values, traversing node operations, and Css-Dom operations.

    1. Attribute operations attr () and removeAttr ()

    The attr () method can obtain element attributes and set element attributes. The method is as follows. When the attr (para1) method has a parameter, it is used to obtain the para1 attribute value of the current element. WhenAttr (para1, attrValue)When there are two parameters, set the attribute value of the current element to "attrValue". For example:

     $("p").attr("title");

    This example is used to obtain the title attribute value of the p element.

    $ ("P"). attr ("title", "your favorite fruit ");

    In this example, set the title attribute value of the p element to "your favorite fruit ";

    If you set multiple attribute values at a time, you can use the name/value pair format, for example:

    $ ("P"). attr ({"title": "your favorite fruit", "name": "Fruit "})

    This example sets two attribute values at a time.

    The removeAttr () method is used to delete a specific attribute by specifying the attribute name in the parameter. Example:

    $("p").removeAttr("name");

    This method removes the name attribute of the p element.

    2. style operations addClass (), removeClass (), toggleClass (), and hasClass ()

    Add style addClass () method. Use this method to add the corresponding style to the target element. The method is as follows:

    $(element).addClass();

    Example:

    $("p").addClass("ul");

    In this example, set the style of element p to ul.

    Remove StyleRemoveClass ()Method to remove the specified style of the target element. The method is as follows:

    $(element).removeClass();

    Example:

     $("p").removeClass("ul");

    Remove the ul style of the p element.

    Change styleToggleClass ()To switch the style of the target element. The method is as follows:

    $(element).toggleClass();

    Example:

    $("p").toggleClass("ul");

    This method switches back and forth [add Delete implement switch] The style ul of element p.

    Determines whether a style is used for an element.$ (Element). hasClass (),The method is as follows:

    $(element).hasClass(class);

    Example:

    alert($("p").hasClass("ul"));

    Print whether the p element has UL style.

          PS: The addClass () and attr () methods have different styles. the attr method sets the attribute value corresponding to the attribute name of an element to the parameter value in the method, and addClass () sets the attribute value.

    Add to the property value corresponding to the property name. Example: existing element

    Element Style

    , Use attr () and addClass () to add new styles respectively.

    $("p").attr("class","another").

    The result is

    Element Style

    $("p").addClass("class","another")

    The result is

    Element Style

    3. Set and obtain HTML [html ()], text [text ()], and value [val ()]

    The html () method gets or sets the html element of an element. The method is as follows:

    $(selector).html();

    Example:

    $ ("P" ).html (); this example obtains the html content of element p.

    $ ("P" 2.16.html ("Add html content"). In this example, set the html content of p"Add html content";

         PS: This method can be used for XHTML documents and cannot be used for XML documents.

    The text () method gets or sets the text value of an element. The method is as follows: $ (selecotr). text (); example:

    $ ("P"). text (); this example obtains the text content of element p.

    $ ("P"). text ("Reset text content"); this example sets the text of element p to "Reset text content ";

    PS: This method applies to both html and XML documents.

    The val () method is used to obtain or set the value of an element. If multiple values are selected, the value is returned as an array. The method is as follows: $ (selector). val (); example: text element

    $ ("# UserName"). val (); obtain the value of the input element.

    $ ("# UserName"). val ('xiangma'); set the value of the input element to 'xiangma '.

    The val () method can operate not only input, but also select [drop-down list box], checkbox [multiple selection box], and radio [single choice ].

    For example, in the drop-down box, select multiple assignment applications.

    AppleBananasWatermelon

    $ ("# Fruits"). val (['apple', 'Banana ']); this example selects the apple and banana items in the select statement.

    4. Traverse nodes for children (), next (), prev (), siblings (), and closest ()

    The children () method is used to obtain the child element set of the matching element. Only child elements are matched without any descendant elements. The method is as follows:

    $(selector).children();

    Example:

     $("$("body").children().length;

    This example obtains the number of child elements of the body element;

    The next () method is used to match the next sibling node of an element. The method is as follows:

    $(selector).next();

    Example:

    $("p").next().html();

    In this example, the html content of the next sibling node of the p element is obtained.

    The prev () method is used to match the previous sibling node of an element. The method is as follows:

    $(selector).prev();

    Example:

    $("ul").prev().text();

    In this example, the text content of the last sibling node of the ul element is obtained.

    The siblings method () is used to match all the sibling elements of the target element. The method is as follows:

    $(selector).siblings();

    Example:

    $ ("P"). slibings (); The example obtains all the sibling node elements of the p element.

    The closest () method () is used to obtain the most recent Matching Element. First, check whether the current element matches. If it matches, the system returns the result directly. Otherwise, the system continues to search for the element that matches the condition in the parent element and returns the result, if no matching element exists, an empty JQuery object is returned.

    5. CSS-Dom operations: css (), offset (), position (), scrollTop (), and scrollLeft ()

    The css () method is used to obtain and set one or more attributes of an element. The method is as follows:

    $(selector).css();

    Example:

    $("p").css("color","red");

    This example is used to set the color attribute of an element to red;

    $ ("P" ).css ("color") This example is used to obtain the color Style value of an element;

    $("p").css({"font-size":"30px","backgroundColor","#888888"});

    This example is used to set multiple styles of an element.

    The offset () method is used to obtain the offset of an element relative to the current form. The returned object includes two attributes: top and left.

    The method is as follows:

    $(selector).offset()

    This example is used to obtain the offset of element p.

    PS: offset () is only valid for visible elements.

    The position () method is used to obtain the relative offset of the last position style attribute of an element set to relative or absolute. The method is as follows:

    $(selector).position();

    Example:

    var postion = $("p").positon();var left=positon.left;var top=positon.top;

    This example is used to obtain the position of element p.

    The scrollTop () and scrollLeft () methods are used to obtain the distance between the scroll bar of an element from the top and the left. The method is as follows:

    $(selector).scrollTop();$(selector).scrollLeft();

    Example:

    var scrollTop=$("p").scrollTop();var scrollLeft=$("p").scrollLeft();

    This example is used to obtain the position of the element's scroll bar.

    You can also add a parameter to scroll the element to the specified position. Example:

    $("textarea").scrollTop(300);$("textarea").scrollLeft(300);

    The above is the DOM operation in the basic Jquery tutorial. I hope it will be helpful to you.

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.