< script>(function($){"/> < script>(function($){">
HomeWeb Front-endJS TutorialSimple and easy-to-understand jQuery: jQuery operations

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:php;toolbar: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:php;toolbar: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 id="Exploring-the-text-method">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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment