Home > Web Front-end > JS Tutorial > body text

How does jQuery's prev() method work?

王林
Release: 2024-02-27 13:36:04
Original
492 people have browsed it

How does jQuerys prev() method work?

jQuery's prev() method is a method used to obtain the sibling elements immediately preceding each element in the matching element set. This method only returns the immediate previous sibling element, that is, the previous sibling element. Below we use specific code examples to illustrate how jQuery's prev() method works.

First, we prepare a simple HTML structure containing three adjacent div elements:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery的prev()方法示例</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div id="div1">第一个div</div>
<div id="div2">第二个div</div>
<div id="div3">第三个div</div>

<script>
$(document).ready(function(){
  var prevElement = $('#div2').prev();
  console.log(prevElement.text());
});
</script>
</body>
</html>
Copy after login

In the above code, we use the jQuery library, and after the document is loaded A function was executed. In this function, we select the div element with id div2 and use the prev() method to obtain the previous sibling element. Finally, print the text content of the obtained element to the console.

When we run the above code, "the first div" will be output in the console. This is because the prev() method obtains the sibling element in front of div2, that is, div1, through the prev() method. The div1 element is obtained and its text content is printed.

To sum up, jQuery’s prev() method can easily obtain the sibling elements before an element, making the positioning and operation of elements during the front-end development process more flexible and convenient.

The above is the detailed content of How does jQuery's prev() method work?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template