< script>(function($){"/> < script>(function($){">

Home  >  Article  >  Web Front-end  >  Simple and easy-to-understand jQuery: jQuery operations

Simple and easy-to-understand jQuery: jQuery operations

WBOY
WBOYOriginal
2023-09-03 22:09:12635browse

Simple and easy-to-understand jQuery: jQuery operations

Dynamicly create, manipulate and add HTML

You can dynamically create HTML markup by passing a raw HTML string to a jQuery function.

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function($){
      alert($('<div><a></a></div>').get(0).nodeName); // Alerts "DIV"
      alert($('<div><a></a></div>').length); // Alerts "1" <div> is in the wrapper set
      alert($('<div><a></a></div><div><a></a></div>').length); // Alerts "2" <div> are in the set
  })(jQuery); </script>
</body>
</html>

It should be noted that when using jQuery functions to create a DOM structure, only the root element in the structure will be added to the wrapper set. In the previous code example, the <div> element would be the only element in the wrapper set. <p>Once any element in the HTML structure is created, we can operate on it using the <code>find() method.

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
        (function ($) {
            $('<div><a></a></div>')
                 .find('a')
                .text('jQuery')
                .attr('href', 'http://www.jquery.com');
        })(jQuery); </script>
</body>
</html>

After manipulating the newly created HTML, you can also use one of jQuery's manipulation methods to add it to the DOM. Below we use the appendTo() method to add the markup to the page.

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function($){  $('<div><a></a></div>')
      .find('a')
      .text('jQuery')
      .attr('href', 'http://www.jquery.com')
      .end().appendTo('body'); // end() is used to exit the find() method
  })(jQuery); </script>
</body>
</html>

Note: Simple elements that do not contain attributes - for example $('<div></div>') - are created via the document.createElement DOM method , while all other cases rely on the innerHTML attribute. In fact, you can directly pass elements created using document.createElement -e.g to jQuery functions. $(document.createElement('div')).

HTML strings passed to jQuery cannot be contained within <div> elements which may be considered invalid. <p>HTML strings passed to jQuery functions must be well-formed. </p> <p>When passing jQuery HTML, you should open and close all HTML elements. Failure to do so may result in errors, primarily in Internet Explorer. To be safe, always close HTML elements and avoid writing shortcut HTML - for example <code>$(<div></div>).


Exploring the index() method

You can determine the index of an element in the wrapped set by passing the element to the index() method. For example, suppose you have a wrapper set that contains all <div> elements in a web page, and you want to know the index of the last <code><div> element. <pre class="brush:html;toolbal:false;"> &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;body&gt; &lt;div&gt;0&lt;/div&gt; &lt;div&gt;1&lt;/div&gt; &lt;div&gt;2&lt;/div&gt; &lt;div&gt;3&lt;/div&gt; &lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script&gt; (function ($) { // Alerts &quot;3&quot; alert($('div').index($('div:last'))); })(jQuery); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </pre> The use of <p><code>index() doesn't really hit home until we consider how to use it with events. For example, by clicking on the <div> element in the code below, we can pass the clicked <code><div> element (using the keyword <code>this) to index() method to determine the index of the clicked <div>. <pre class="brush:html;toolbal:false;"> &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;body&gt; &lt;div id=&quot;nav&quot;&gt; &lt;div&gt;nav text&lt;/div&gt; &lt;div&gt;nav text&lt;/div&gt; &lt;div&gt;nav text&lt;/div&gt; &lt;div&gt;nav text&lt;/div&gt; &lt;/div&gt; &lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script&gt; (function ($) { // Alert index of the clicked div amongst all div's in the wrapper set $('#nav div').click(function () { alert($('#nav div').index(this)); // or, a nice trick... alert($(this).prevAll().length); }); })(jQuery); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </pre> <hr> <h2>Exploring the text() method</h2> <p>People may mistakenly believe that the <code>text() method only returns the text node of the first element in the wrapper set. However, it actually concatenates the text nodes of all elements contained in the wrapper set and returns the concatenated value as a single string. Make sure you understand this feature or you may get some unexpected results.

<!DOCTYPE html>
<html lang="en">
<body>
    <div>1,</div>
    <div>2,</div>
    <div>3,</div>
    <div>4</div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script> (function ($) {
     alert($('div').text()); // Alerts "1,2,3,4"
 })(jQuery); </script>
</body>
</html>

Use regular expressions to update or delete characters

Using JavaScript replace() method combined with some jQuery functionality, we can very easily update or remove any character pattern in the text contained in the element.

<!DOCTYPE html>
<html lang="en">
<body>
    <p>
        I really hate using JavaScript.     I mean really hate it!     It is the best twister
        ever!
    </p>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
var $p = $('p');
      // Replace 'hate' with 'love'
      $p.text($p.text().replace(/hate/ig, 'love'));
      // Remove 'twister' and replace it with nothing
      $p.text($p.text().replace(/twister/ig, ''));   // Keep in mind that text() returns a string, not the jQuery object.
      // That is how the replace() string method is chained after using text()
  })(jQuery); </script>
</body>
</html>

You can also update any characters contained in the string returned from html(). This means you can not only update text, but also update and replace DOM elements via regular expressions.


Exploring .contents() method

The

.contents() method can be used to find all child element nodes, including text nodes contained within the element. However, there is a problem. If the retrieved content contains only text nodes, the selection will be placed in the wrapper set as a single text node. However, if the content you are retrieving contains one or more element nodes within a text node, the .contents() method will contain both text nodes and element nodes. Check the code below to grasp this concept.

<!DOCTYPE html>
<html lang="en">
<body>
    <p>I love using jQuery!</p>
    <p>I love <strong>really</strong> using jQuery!</p>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      // Alerts "I love using jQuery!" because no HTML elements exist
      alert($('p:first').contents().get(0).nodeValue);
      // Alerts "I love"
      alert($('p:last').contents().get(0).nodeValue);
      // Alerts "really" but is an HTML element, not a text node
      alert($('p:last').contents().eq(1).text());
      // Alerts "using jQuery!"
      alert($('p:last').contents().get(2).nodeValue);
  })(jQuery); </script>
</body>
</html>

Please note that when the item in the wrapper set is a text node, we must use .get(0).nodeValue to extract the value. contents() The method is convenient for extracting text node values. You can use contents() to extract only text nodes from the DOM structure.

<!DOCTYPE html>
<html lang="en">
<body>
    <p>jQuery gives me <strong>more <span>power</span></strong> than any other web tool!
    </p>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function($){  $('p')  .find('*') // Select all nodes
      .andSelf() // Include <p>
      .contents() // Grab all child nodes, including text
      .filter(function() {return this.nodeType == Node.TEXT_NODE;}) // Remove non-text nodes
      .each(function (i, text) { alert(text.nodeValue) }); // Alert text contained in wrapper set
  })(jQuery); </script>
</body>
</html>

Using remove() will not remove elements from the packed set

When you use remove(), elements contained in the DOM structure from which the DOM fragment has been removed are still included in the wrapper set. You can remove an element, perform operations on that element, and then actually put the element back into the DOM, all within a single jQuery chain.

<!DOCTYPE html>
<html lang="en">
<body>
    <div>remove me</div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      $('div')
          .remove().html('<a href="http://www.jQuery.com">jQuery</a>')
          .appendTo('body');
  })(jQuery); </script>
</body>
</html>

The point here is that just because you remove() elements doesn't mean they have been removed from the jQuery wrapper set.

The above is the detailed content of Simple and easy-to-understand jQuery: jQuery operations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn