Home > Web Front-end > JS Tutorial > Share the difference between parent and parents in jquery

Share the difference between parent and parents in jquery

黄舟
Release: 2017-06-23 15:32:48
Original
1659 people have browsed it

It can be seen that the value of parent is very clear, which is the parent element of the current element; parents is the ancestor element of the current element. Examples are listed below:

<p id=&#39;p1&#39;>
<p id=&#39;p2&#39;><p></p></p>
<p id=&#39;p3&#39; class=&#39;a&#39;><p></p></p>
<p id=&#39;p4&#39;><p></p></p>
</p>
Copy after login


$('p').parent() gets p2, p3, p4
$('p').parent('.a ') gets p3
$('p').parent().parent() gets p1, which is rather strange; but JqueryObject Its own characteristics determine that this is feasible.
$('p').parents() gets p1, p2, p3, p4
$('p').parents('.a') gets p3
parent (exp) Usage: Get an element set containing the unique parent element of all matching elements.

<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript"> 
$(document).ready(function() {
$("#btn1").click(function(){
alert($(this).parent().next().html());
});
});
</script> 
</head> 
<body> 
<table>
<tr>
      <td><input id="btn1"  class="btn" type="button"  value="test" /></td>
      <td>some text</td>
</tr>
</table>
Copy after login

Among them:
this.parent() is the td in front of the input
this.parent().parent() obtains tr
this.parent().parent() .parent() obtains table
this.parent().next() obtains td
adjacent to td. In the example:

<p><p>Hello</p><p>Hello</p></p>
Copy after login

$("p") .parent() gets: <p><p>Hello</p><p>Hello</p></p> object, because the parent tag of the p tag is p

Using jquery’s parents()

I encountered an interesting problem today. jquery has two functions parent() and parents(). Through these two functions, you can find the parent object of an object. Also known as jquery's selector. For example:

<body>
<div id="one">
<div id="two">hello</div>
<div id="three">
<p>
<a href="#">tonsh</a>
</p>
</div>
</div>
Copy after login

$("a").parent() will get the parent object


$("a").parents() will get the parent object
$("a").parents().filter("div") will get, which is OK Written as $("a").parents("div").
If you want the object, you can write it like this: $("a").parents("div:eq(0)").
What should I do if the content in pops up when I click the link?


The above is the detailed content of Share the difference between parent and parents in jquery. 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