[jQuery] Specify the order of child elements and get them

スポンサーリンク
programming/coding
スポンサーリンク
Let's try getting multiple child elements in various ways.

mainly
eq()⇒Specify a number and get the number
index()⇒Get the number
I'm going to use it.

HTML source
<div id="outer">
	<span>in1</span>
	<div>in2</div>
	<p>in3</p>
	<div class="childe">in4</div>
	<span class="childe">in5</span>
	<div>in6</div>
	<p>in7</p>
</div>

js source

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
	//Store parent element
	var parent_e = $('#outer');
	//Output the contents by specifying the number with children().eq()
	console.log($(parent_e).children().eq(0).text()); //⇒「in1」output
	console.log($(parent_e).children().eq(6).text()); //⇒「in7」output
	
	//Get the number with index()
	console.log($(parent_e).children('span').index()); //⇒「0」output
	console.log($(parent_e).children('div').index()); //⇒「1」output
	console.log($(parent_e).children('p').index()); //⇒「2」output
	console.log($(parent_e).children('.childe').index()); //⇒「3」output
	console.log($(parent_e).children().index()); //⇒「0」output
	
	//Output the contents by combining eq() and index()
	console.log($(parent_e).children().eq($(parent_e).children('span').index()).text()); //⇒「in1」output
	console.log($(parent_e).children().eq($(parent_e).children('div').index()).text()); //⇒「in2」output
	console.log($(parent_e).children().eq($(parent_e).children('.childe').index()).text()); //⇒「in4」output
});
</script>

Get child elements from parent element with children().

There are multiple child elements, so you can retrieve that element by specifying the number with eq().

You can also specify a tag for index(), but be careful as it will return -1 if the parent element and child element are the same.
In the above, it can be obtained by specifying the tag with children().

Note that the order of both eq and index starts from 0.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
	//Store parent element
	var parent_e = $('#outer');
	console.log($(parent_e).children('div').index()); //⇒「1」output
	console.log($(parent_e).children().index($('div'))); //⇒「-1」output
	console.log($(parent_e).children('p').index()); //⇒「2」output
	console.log($(parent_e).children().index($('p'))); //⇒「2」output
});
</script>

Also, index() returns the first occurrence, so if there are multiple matching items, you will need another method.

コメント

Copied title and URL