Home > Web Front-end > Front-end Q&A > What are the traversal methods in jquery?

What are the traversal methods in jquery?

青灯夜游
Release: 2023-03-15 13:59:45
Original
2107 people have browsed it

The traversal methods are: 1. add(), used to add elements to the set of matching elements; 2. children(), used to return all direct child elements of the selected element; 3. closest() ), used to return the first ancestor element of the selected element; 4. contents(), used to return all direct child elements of the selected element; 5. each(), used to execute the function for each matching element; 7 , eq(); 8. find(); 9. first(); 10. is(); 11. last() and so on.

What are the traversal methods in jquery?

The operating environment of this tutorial: windows7 system, jquery3.6 version, Dell G3 computer.

jQuery traversal method summary

jQuery traversal functions include methods for filtering, finding, and concatenating elements.

##children() Returns all direct child elements of the selected element## closest()contents()each()end()eq()filter()find()first()has()is()last()map()next()##nextAll() Returns all sibling elements after the selected elementnextUntil()Returns each element between the two given parameters All sibling elements after the elementnot()Remove the element from the set of matching elementsoffsetParent( )Returns the first positioned parent elementparent()Returns the direct parent element of the selected elementparents()Returns all ancestor elements of the selected elementparentsUntil()Returns between two given All ancestor elements between the specified parametersprev()Returns the previous sibling element of the selected elementprevAll()Returns all sibling elements before the selected elementprevUntil()Returns between the two given parameters All sibling elements before each element between Returns all sibling elements of the selected elementReduce the set of matching elements to a subset of the specified range
Method Description
add() Adds an element to the matching element In the collection
addBack() Add the previous set of elements to the current collection
andSelf() Deprecated in version 1.8. Alias ​​for addBack()
Returns the first ancestor element of the selected element
Returns all direct child elements of the selected element ( Contains text and comment nodes)
Execute the function for each matching element
End the latest filtering operation in the current chain, and return the set of matching elements to the previous state
Return with The element with the specified index number of the selected element
Reduce the set of matching elements to new elements matching the selector or the return value of the matching function
Returns the descendant elements of the selected element
Returns the selected element The first element
Returns all elements that have one or more elements inside it
Checks the set of matching elements based on the selector/element/jQuery object, and returns true if there is at least one matching element
Return the last element of the selected element
Pass each element in the current matching set to the function and generate a return value The new jQuery object
Returns the next sibling element of the selected element
##siblings()
slice()

Two methods for traversing child elements

  • children() method: Get the direct subset elements under the element

  • find() method: Get all subset elements (including subsets of subsets) under the element

Difference:

children() method Return Returns all direct child elements of the selected element (direct child elements, only look for sons and not grandchildren (: that is to say, it will not traverse recursively)

find() method obtains each element in the current element collection Descendants of elements (note that the find() method must pass parameters, otherwise it will be invalid)

Example: Query all child elements

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<style>
			div * {
				display: block;
				border: 2px solid lightgrey;
				color: lightgrey;
				padding: 5px;
				margin: 15px;
			}
		</style>

		<script>
			$(document).ready(function() {
				$("button").on("click", function() {
					$("ul").find("*").css({
						"color": "red",
						"border": "2px solid red"
					});
				});
			});
		</script>
	</head>

	<body class="ancestors">
		<div style="width:500px;">div (父节点)
			<ul>ul (指定元素)
				<li>li (子节点1)
					<span>span (孙节点1)</span>
				</li>
				<li>li (子节点2)
					<span>span (孙节点2)</span>
				</li>
				<li>li (子节点3)
					<span>span (孙节点3)</span>
				</li>
			</ul>
		</div>
		<button>选取ul的所有子元素</button>
	</body>

</html>
Copy after login

What are the traversal methods in jquery?

7 methods of traversing sibling elements:

  • siblings() method, mainly used to obtain all elements of the same level of a specified element

  • next() method, mainly used to obtain the next sibling element of the specified element

  • nextAll() method, mainly used to obtain all elements of the next sibling level of the specified element

  • nextUntil() method is mainly used to obtain the next sibling element of the specified element. This sibling element must be the element between the specified element and the element set by the nextUntil() method.

  • prev() method, mainly used to obtain the upper level sibling elements of the specified element

  • prevAll() method, mainly used Obtain all the sibling elements at the previous level of the specified element.

  • prevUntil() method is mainly used to obtain the previous sibling element of the specified element. This sibling element must be the same as the specified element. Elements between elements set by the prevUntil() method

##siblings() method

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
	</head>

	<body>
		<div><span>Hello</span></div>
		<p class="selected">Hello Again</p>
		<p>And Again</p>

		<script>
			$("p").siblings(".selected").css("background", "yellow");
		</script>

	</body>
</html>
Copy after login

What are the traversal methods in jquery?##next() method

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
	</head>

	<body>
		<ul>
			<li>list item 1</li>
			<li>list item 2</li>
			<li class="third-item">list item 3</li>
			<li>list item 4</li>
			<li>list item 5</li>
		</ul>

		<script>
			$(&#39;li.third-item&#39;).next().css(&#39;background-color&#39;, &#39;red&#39;);
		</script>

	</body>
</html>
Copy after login

What are the traversal methods in jquery?nextAll() method

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
	</head>

	<body>

		<ul>
			<li>list item 1</li>
			<li>list item 2</li>
			<li class="third-item">list item 3</li>
			<li>list item 4</li>
			<li>list item 5</li>
		</ul>

		<script>
			$(&#39;li.third-item&#39;).nextAll().css(&#39;background-color&#39;, &#39;red&#39;);
		</script>

	</body>
</html>
Copy after login

What are the traversal methods in jquery?nextUntil() method

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
		<style>
			.siblings * {
				display: block;
				border: 2px solid lightgrey;
				color: lightgrey;
				padding: 5px;
				margin: 15px;
			}
		</style>
		<script>
			$(document).ready(function() {
				$("li.start").nextUntil("li.stop").css({
					"color": "red",
					"border": "2px solid red"
				});
			});
		</script>
	</head>
	<body>

		<div style="width:500px;" class="siblings">
			<ul>ul (父节点)
				<li>li (兄弟节点)</li>
				<li>li (兄弟节点)</li>
				<li class="start">li (类名为"start"的兄弟节点)</li>
				<li>li (类名为"start"的li节点的下一个兄弟节点)</li>
				<li>li (类名为"start"的li节点的下一个兄弟节点)</li>
				<li>li (类名为"start"的li节点的下一个兄弟节点)</li>
				<li class="stop">li (类名为"stop"的兄弟节点)</li>
			</ul>
		</div>
		<p>在这个例子中,我们返回在类名为“star”和类名为“stop”的 li元素之间的所有下一个兄弟元素。</p>

	</body>
</html>
Copy after login

What are the traversal methods in jquery?prev() method

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
		<style>
			.siblings * {
				display: block;
				border: 2px solid lightgrey;
				color: lightgrey;
				padding: 5px;
				margin: 15px;
			}
		</style>
		<script>
			$(document).ready(function() {
				$("li.start").prev().css({
					"color": "red",
					"border": "2px solid red"
				});
			});
		</script>
	</head>
	<body>

		<div style="width:500px;" class="siblings">
			<ul>ul (父节点)
				<li>li (兄弟节点)</li>
				<li>li (类名为"start"的li节点的上一个兄弟节点)</li>
				<li class="start">li (类名为"start"的li节点)</li>
				<li>li (兄弟节点)</li>
				<li>li (兄弟节点)</li>
			</ul>
		</div>

	</body>
</html>
Copy after login

What are the traversal methods in jquery?prevAll() method

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
		<style>
			.siblings * {
				display: block;
				border: 2px solid lightgrey;
				color: lightgrey;
				padding: 5px;
				margin: 15px;
			}
		</style>
		<script>
			$(document).ready(function() {
				$("li.start").prevAll().css({
					"color": "red",
					"border": "2px solid red"
				});
			});
		</script>
	</head>
	<body>

		<div style="width:500px;" class="siblings">
			<ul>ul (parent)
				<li>li (类名为"start"的li的上一个兄弟节点)</li>
				<li>li (类名为"start"的li的上一个兄弟节点)</li>
				<li>li (类名为"start"的li的上一个兄弟节点)</li>
				<li class="start">li (类名为"start"的li节点)</li>
				<li>li (兄弟节点)</li>
				<li>li (兄弟节点)</li>
			</ul>
		</div>
		<p>在这个例子中,我们返回类名称为“star”的li元素之前的所有兄弟元素。</p>

	</body>
</html>
Copy after login

What are the traversal methods in jquery?prevUntil() method

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
		<style>
			.siblings * {
				display: block;
				border: 2px solid lightgrey;
				color: lightgrey;
				padding: 5px;
				margin: 15px;
			}
		</style>
		<script>
			$(document).ready(function() {
				$("li.start").prevUntil("li.stop").css({
					"color": "red",
					"border": "2px solid red"
				});
			});
		</script>
	</head>
	<body>

		<div style="width:500px;" class="siblings">
			<ul>ul (父节点)
				<li class="stop">li (类名为"stop"的兄弟节点)</li>
				<li>li (类名为"start"的li节点的上一个兄弟节点)</li>
				<li>li (类名为"start"的li节点的上一个兄弟节点)</li>
				<li>li (类名为"start"的li节点的上一个兄弟节点)</li>
				<li class="start">li (类名为"start"的li节点)</li>
				<li>li (兄弟节点)</li>
				<li>li (兄弟节点)</li>
			</ul>
		</div>
		<p>在这个例子中,我们返回在类名为“star”和“stop”的li元素之间的所有上一个兄弟元素,。</p>

	</body>
</html>
Copy after login

What are the traversal methods in jquery?

each() and map() methods can traverse the array

each() traverse the array

<script>
	var arr = [1,3,5,7,9];
	var obj = {0:1,1:3,2:5,3:7,4:9};

	/**
	* 利用jQuery的each静态方法遍历
	* 第一个参数:当前遍历到的索引
	* 第二个元素:遍历到的元素
	* 注意:jQuery的each方法可以遍历伪数组
	*/
	$.each(arr,function(index,value){
		console.log("jQuery-each方法遍历数组:",index,value);
	})
	$.each(obj,function(index,value){
		console.log("jQuery-each方法遍历伪数组:",index,value);
	})
</script>
Copy after login

What are the traversal methods in jquery?map() traverses the array

<script>
	var arr = [1,3,5,7,9];
	var obj = {0:1,1:3,2:5,3:7,4:9};
	/**
	*1.利用原生JS的map方法遍历 
	*第一个参数:遍历到的元素
	*第二个参数:当前遍历到的索引
	*第三个参数:当前被遍历的数组
	*注意:和原生的forEach方法一样,不能遍历伪数组
	*/
	arr.map(function(value,index,array){
		console.log("原生map遍历数组:",index,value,array);
	});
	/**
	obj.map(function(value,index,array){
		console.log("原生map遍历伪数组:",index,value,array);
		//Uncaught TypeError: obj.forEach is not a function
	});
	*/

	/**
	* 2.利用jQuery的each静态方法遍历
	* 第一个参数:要遍历的数组
	* 每遍历一个元素之后执行的回调函数
	* 回调函数的参数:
	* 	第一个参数:遍历到的元素
	* 	第二个元素:当前遍历到的索引
	* 注意:和jQuery的each方法一样可以遍历伪数组
	*/
	$.map(arr,function(value,index){
		console.log("jQuery-map方法遍历数组:",index,value);
	})
	$.map(obj,function(value,index){
		console.log("jQuery-map方法遍历伪数组:",index,value);
	})
</script>
Copy after login

What are the traversal methods in jquery?

##Expand knowledge: usage of each

1. Each

复制代码

 var arr = [ "one", "two", "three", "four"];     
 $.each(arr, function(){     
    alert(this);     
 });   
//上面这个each输出的结果分别为:one,two,three,four    
    
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]     
$.each(arr1, function(i, item){     
   alert(item[0]);     
});     
//其实arr1为一个二维数组,item相当于取每一个一维数组,   
//item[0]相对于取每一个一维数组里的第一个值   
//所以上面这个each输出分别为:1   4   7     
  
  
var obj = { one:1, two:2, three:3, four:4};     
$.each(obj, function(i) {     
    alert(obj[i]);           
});   
//这个each就有更厉害了,能循环每一个属性     
//输出结果为:1   2  3  4
Copy after login

in the array 2. Traverse the Dom elements

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("li").each(function(){
      alert($(this).text())
    });
  });
});
</script>
</head>
<body>
<button>输出每个列表项的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
</body>
</html>
Copy after login
Pop up Coffee, Milk, and Soda in turn

3. Comparison of each and map

The following example is to obtain each ID value of multiple boxes;

each method:

Define an empty array and add ID values ​​to the array through each method; finally After the array is converted into a string, alert this value;

$(function(){
    var arr = [];
    $(":checkbox").each(function(index){
        arr.push(this.id);
    });
    var str = arr.join(",");
    alert(str);
})
Copy after login
map method:

Execute each: checkbox return this.id; And automatically save these return values ​​as jQuery objects, then use the get method to convert them into native Javascript arrays, then use the join method to convert them into strings, and finally alert the value;

$(function(){
    var str = $(":checkbox").map(function() {
        return this.id;
    }).get().join();    
    alert(str);
})
Copy after login
When you need the value of an array, use the map method, which is very convenient.

4. Use each

in jquery to traverse the array, using both element index and content. (i is the index, n is the content)

The code is as follows:

$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});
Copy after login

Example the object, using both member names and variable contents. (i is the member name, n is the variable content)

The code is as follows:

$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});
Copy after login

Example of traversing the dom element, here an input form element is used as an example.

If you have a piece of code like this in your dom

<input name="aaa" type="hidden" value="111" /> 
<input name="bbb" type="hidden" value="222" /> 
<input name="ccc" type="hidden" value="333" /> 
<input name="ddd" type="hidden" value="444"/>
Copy after login

Then you use each as follows

The code is as follows:

$.each($("input:hidden"), function(i,val){
alert(val); //输出[object HTMLInputElement],因为它是一个表单元素。
alert(i); //输出索引为0,1,2,3
alert(val.name); //输出name的值
alert(val.value); //输出value的值
});
Copy after login

5.Find elements based on this in each

实现效果”回复”两个字只有在鼠标经过的时候才显示出来

<ol class="commentlist">
    <li class="comment">
        <div class="comment-body">
          <p>嗨,第一层评论</p>
          <div class="reply">
            <a href="#" class=".comment-reply-link">回复</a>
          </div>
        </div>
        <ul class="children">
          <li class="comment">
            <div class="comment-body">
            <p>第二层评论</p>
            <div class="reply">
              <a href="#" class=".comment-reply-link">回复</a>
            </div>
          </div></li>
        </ul>
    </li>
</ol>
Copy after login

js代码如下

$("div.reply").hover(function(){
  $(this).find(".comment-reply-link").show();
},function(){
  $(this).find(".comment-reply-link").hide();
});
Copy after login

实现效果,验证判断题是否都有选择

html

<ul id="ulSingle">
    
            <li class="liStyle">
                1.  阿斯顿按时<label id="selectTips" style="display: none" class="fillTims">请选择</label>
                <!--begin选项-->
                <ul>
                    
                            <li class="liStyle2">
                                <span id="repSingle_repSingleChoices_0_labOption_0">A         </span>.阿萨德发<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl00$hidID" id="repSingle_repSingleChoices_0_hidID_0" value="1" />
                                <input id="repSingle_repSingleChoices_0_cheSingleChoice_0" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl00$cheSingleChoice" /></li>
                        
                            <li class="liStyle2">
                                <span id="repSingle_repSingleChoices_0_labOption_1">B         </span>.阿萨德发<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl01$hidID" id="repSingle_repSingleChoices_0_hidID_1" value="2" />
                                <input id="repSingle_repSingleChoices_0_cheSingleChoice_1" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl01$cheSingleChoice" /></li>
                        
                            <li class="liStyle2">
                                <span id="repSingle_repSingleChoices_0_labOption_2">C         </span>.阿斯顿<input type="hidden" name="repSingle$ctl00$repSingleChoices$ctl02$hidID" id="repSingle_repSingleChoices_0_hidID_2" value="3" />
                                <input id="repSingle_repSingleChoices_0_cheSingleChoice_2" type="checkbox" name="repSingle$ctl00$repSingleChoices$ctl02$cheSingleChoice" /></li>
                        
                </ul>
                <!--end选项-->
                <br />
            </li>
        
</ul>
Copy after login

js代码

//验证单选题是否选中
        $("ul#ulSingle>li.liStyle").each(function (index) {
            //选项个数
            var count = $(this).find("ul>li>:checkbox").length;
            var selectedCount = 0
            for (var i = 0; i < count; i++) {
                if ($(this).find("ul>li>:checkbox:eq(" + i + ")").attr("checked")) {
                    selectedCount++;
                    break;
                }
            }
            if (selectedCount == 0) {
                $(this).find("label#selectTips").show();
                return false;
            }
            else {
                $(this).find("label#selectTips").hide();
            }
        })
Copy after login

ps:传说中attr("property", "value");在部分浏览器中不管用可以用prop,如果只是判断可以用$(this).find("ul>li>:checkbox:eq(" + i + ")").is(":checked");

6.官方解释
以下是官方的解释:

jQuery.each(object, [callback])
Copy after login

概述 

通用例遍方法,可用于例遍对象和数组。

不同于例遍 jQuery 对象的 $().each() 方法,此方法可用于例遍任何对象。回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内容。如果需要退出 each 循环可使回调函数返回 false,其它返回值将被忽略。 

参数 

  • objectObject :需要例遍的对象或数组。 

  • callback (可选)Function :每个成员/元素执行的回调函数。

【推荐学习:jQuery视频教程web前端视频

The above is the detailed content of What are the traversal methods in jquery?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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